Hey guys,
I'm trying to create a program that allows the user to enter the size of an array and then enter the contents of each subscript. after doing that, the program will check which entry is an even number (after each number entry) and create a new array, the size depending on the even number amount. Once it does that, it checks again through the original array and for each array that is even, it places the number in the new array. However when I compile my program, for testing purposes I output the evenCount and it gives 10x whatever even numbers there are.. also I get an Array out of bounds exception which I don't think should happen after looking at my code over and over again. Could I get a second opinion on my code?
Thanks
import java.util.Scanner; public class AllEven { public static void main (String[]args) { int evenCount =0; Scanner kybd = new Scanner(System.in); System.out.print("Enter size of first array: "); int size1 = kybd.nextInt(); int[] array = new int[size1]; System.out.println(); System.out.print("Enter contents of first array: "); read(array, evenCount); System.out.print("Number of even numbers in array: " + read()); System.out.println(evenCount); int[] evenArray = new int [evenCount]; System.out.println(); getEven(array, evenArray); print(evenArray); } public static int read(int[] arr, int even) { Scanner kybd = new Scanner(System.in); for (int i = 0; i < arr.length; i++) { arr[i] = kybd.nextInt(); double OddOrEven = arr[i] % 2; if (OddOrEven > 0) { System.out.println(); } else { even++; } } System.out.print("Number of even numbers in array: " + even); return even; } public static int[] getEven(int[] arr, int[]EveArray) { int a = 0; System.out.println("TESTING1"); for (int x = 0; x < arr.length; x++) { System.out.println("TESTING2"); //for (int a = 0; a < EveArray.length; a++) System.out.println("TESTIN3"); double oddOrEven = arr[x] % 2; if (oddOrEven > 0) { System.out.println("number not copied over, as its not even"); } else { System.out.println("TESTING4"); System.out.println("TESTING5"); EveArray[a] = arr[x]; EveArray[a]++; } } return EveArray; } public static void print(int[] EveArray) { for (int i = 0; i < EveArray.length; i++) { System.out.print(EveArray[i] + " "); } System.out.println(); } }
Results:
helpmeee!.jpg