Blake B. Blake B. - 2 months ago 9
Java Question

Using For-loops to get integers from user, then printing the even numbers

This is what I have so far:

import java.util.Scanner;
public class evenArray
{//begin class
public static void main(String[]args)
{//begin main method
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println();

System.out.println("Please enter the number of intergers you want to put into the array.");
int numbers = input.nextInt();
int[] arrayInt = new int[numbers];
int i = 0;

System.out.println("Please enter the numbers to enter into the array.");
for (i =1; i < arrayInt.length; i++){
arrayInt[i] = input.nextInt();
}

int evenNumber = 0;
for ( i = 0; i < arrayInt.length; i++){
if(arrayInt[i] % 2 == 0){
evenNumber++;
System.out.println("The even numbers are " + evenNumber);
}
}

}

}


It compiles fine, but this is what prints:

dhh005@cs:~$ java evenArray

Please enter the number of intergers you want to put into the array.
6
Please enter the numbers to enter into the array.
10
-7
3
42
-20
The even numbers are 1
The even numbers are 2
The even numbers are 3
The even numbers are 4


I cant figure out why it isn't showing the actual even numbers. Any help would be appreciated.

Answer

Replace

System.out.println("The even numbers are " + evenNumber); 

with

System.out.println("The even numbers are " + arrayInt[i]);

And you can remove the evenNumber variable altogether.