I apologize if my code is messy, as I am very new to Java and have also been editing out parts of my code to see if I can make it work. I have an assignment in which I have to generate 100
random integers in between 0
and 25
and store them in an array. Then, I have to create another method that sorts out the even integers into a separate array, then do this with the odds in another method.
My problem is, no matter how hard I try, I cannot manage to get my even sorting method to recognize the original array with the 100
random integers. The command prompt says it requires int[]
but found int. I even tried making the sortEvens method require an integer instead of an array and the prompt said the exact opposite. Here is my code:
public class AssignmentEight
{
public static void main (String[] args)
{
final int NUMBER_OF_ELEMENTS = 100;
int numbers[];
int evens[];
int odds[];
numbers = new int[100];
for (int n = 0; n < numbers.length; n++)
{
numbers[n] = (int)(Math.random() * 25);
}
evens = sortEvens (numbers);
display (evens);
}
public static int sortEvens (int a[])
{
int evens[];
for (int n = 0; n < 100; n++)
{
int x = (a[n] % 2);
if (x == 0)
{
evens[n] = a[n];
}
}
return evens;
}
public static void display (int array[])
{
for (int n = 0; n < array.length; n++)
System.out.print(array[n]);
System.out.print("\t");
}
}
I apologize if this doesn't make sense. My main problem is that I cannot compile my program. I will try to provide further details if necessary.
Your sortEvens()
method needs to return an int[]
. You've also forgotten to initialize your array.
public static int[] sortEvens (int a[]) {
int evens[] = new int[100];
// ...
}
In getEvens()
method
if ((x == 0)) // ^ (x == 2)) <-- remove this ^ condition
totalEvens += 1;
for (n = 0; n < a.length; n++) { // loop a.length times; not totalEvens
x = (a[n] % 2);
if (x == 0) { // ADDED
evens[y] = a[n];
y++; // increment only when an even is found
} // ADDED
}
In getOdds()
method
for (n = 0; n < a.length; n++) { // loop a.length times; not totalOdds
x = (a[n] % 2);
if (x == 1) { // ADDED
odds[y] = a[n];
y++; // increment only when an odd is found
} // ADDED
}