Java – 25 even and even random number generator
I need to generate 25 random numbers and divide them into two arrays, depending on whether they are odd or even This is my expected output:
Even: 40 10 70 58 20 18 74 44 14 54 50 42 odd: 21 75 29 69 7 41 33 35 21 13 93 73 33
This is what I have done so far:
public static void main(String[] args) { Scanner input = new Scanner(system.in).useDelimiter("\n"); int[] randomNumbers = new int[25]; int[] evenNumbers = new int[25]; int[] oddNumbers = new int[25]; int k = 0,l = 0; for (int i= 0; i< randomNumbers.length; i++) { randomNumbers[i] = (int) (Math.random() * 99); } for (int i = 0; i < 25; i++) { if (randomNumbers[i] % 2 == 0) { evenNumbers[k] = randomNumbers[i]; k++; } else { oddNumbers[l] = randomNumbers[i]; L++; } }System.out.print("Even: "); for (int i = 0; i< evenNumbers.length; i++) { System.out.print(evenNumbers[i] + " "); }System.out.println(""); System.out.print("Odd: "); for (int i= 0; i < oddNumbers.length; i++) { System.out.print(oddNumbers[i] + " "); } } }
This is my actual output:
Even number: 40 10 70 58 20 18 74 44 14 54 50 42 0 0 0 0 0 0 0 0 0 0 0 0 odd number: 21 75 29 69 7 41 33 35 21 13 93 73 0 0 0 0 0 0 0 0 0 0
I want to know how to get rid of zero at the end of each output
Solution
int [] evenNumbers = new int [25]; An array of 25 integers will be created and initialized to 0
The loop then prints all 25 integers, even if they are not replaced:
for (int i = 0; i< evenNumbers.length; i++) { System.out.print(evenNumbers[i] + " "); }
To fix the loop from 0 to k-1 (for example, I instead of an int array.) Or use list
This also applies to odd numbers. You just need to use I < I change to