Question: A method should accept a one dimensional array as its argument and return the sum of all the odd numbers in the array. and even
A method should accept a one dimensional array as its argument and return the sum of all the odd numbers in the array. and even numbers. I can not get my code to work.
public static void main( String[] args ) {
final int ARRAY_SIZE = 6;
int[] numbers = new int[ARRAY_SIZE]; getValues ( numbers ); getTotal ( numbers ); getAverage ( numbers ); getGreatest ( numbers ); getLeast ( numbers ); getEven ( numbers ); getOdd ( numbers ); }
public static double getTotal( int[] x ) {
int total = 0;
for ( int i = 0; i < x.length; i++ ) {
total += x[i];
}
System.out.println( "The total is " + total );
return total;
}
public static double getAverage( int[] x ) {
int total = 0;
for ( int i = 0; i < x.length; i++ ) {
total += x[i];
}
double average = ( total / 6 );
System.out.println ( "The average is " + average );
return average;
}
public static int getGreatest( int[] x ) {
int greatest = x[0];
for ( int i = 1; i < x.length; i++ ) { if ( x[i] > greatest )
greatest = x[i];
}
System.out.println( "The greatest value is " + greatest );
return greatest;
}
public static int getLeast( int[] x ) {
int least = x[0];
for ( int i = 1; i < x.length; i++ ) {
if ( x[i] < least )
least = x[i];
}
System.out.println( "The least value is " + least );
return least;
} public static int getEven( int[] x ){ for (int i = 0; i < x.length; i++) { if (i % 2 == 0) even += x[i]; else odd += x[i]; }
System.out.println("Even index positions sum: " + even); System.out.println("Odd index positions sum: " + odd); }
private static void getValues( int[] array ) {
Scanner keyboard = new Scanner(System.in);
System.out.println( "Please enter the " + array.length + " test scores." );
for ( int i = 0; i < array.length; i++ ) {
System.out.print( "Score: " + (i + 1) + ": " );
array[i] = keyboard.nextInt();
}
} }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
