Goals The lab this lesson introduces students to array processing. By the end of
ID: 3819396 • Letter: G
Question
Goals
The lab this lesson introduces students to array processing. By the end of this lab, students should be able to
allocate arrays
initialize arrays with random numbers
use Arrays.sort
process arrays from the first element to the last, and also from the last element to the first
average the elements of an array
process command line arguments
Write a program that takes a series of int values as command line arguments. Calculate a total from the values, but add the values that are even, and subtract the values that are odd. Note that you're basing the add/subtract operation on the value, not on the position in the argument list. For example, if you call your class CmdLineProc,
java CmdLineProc 1 2 4 3 5 7 6 8 4 3
should calculate -1+2+4-3-5-7+6+8+4-3
Explanation / Answer
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Array {
public static void main(String[] args) {
int sum = 0;
int a[];
for (int i = 0; i < args.length; i++) {
a[i]= Integer.parseInt(args[i]);
}
for(int i =0;i< a.length;i++){
System.out.print("array["+i+"]"+ a[i] + " "); //parse from first to last
}
System.out.println(" ");
for( int j =a.lenght;j<=0 ;j++){
System.out.print("array["+j+"]"+ a[j] + " "); //parse from last to first
}
System.out.println("The total of the arguments passed is " );
for(int x=0;x<a.length;x++){
sum=sum+check(a[i]);}
System.out.println(sum);
}
public static int check(int n1) {
if(n1%2==0){
return n1;
} else
{
return (-n1);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.