Reputation: 73
I'm trying to figure out how to sort a list of input in one array, and make two different arrays out of that, either into even or odd numbers. I can't seem to add the integers to the array in the if-loop.
Here is my code:
Scanner in = new Scanner (System.in);
System.out.print("Enter a number");
int number = in.nextInt();
int [] x = new int[0];
int [] even = new int [0];
int [] odd = new int [0];
for (int i = 0; i <x.length; i++)
{
if (in.nextInt() == 0){
for (i = 0; i <x.length; i++)
{
if (x[i] % 2 == 0)
{
even = even + x[i];
System.out.print("Even numbers = " + even);
i++;
}
if (x[i] % 2 != 0)
{
odd = odd + x[i];
System.out.print("Odd numbers = " + odd);
i++;
}
}
break;
}
else {
x[i] = number;
i++;
}
}
Upvotes: 1
Views: 6113
Reputation: 4175
Two good solutions:
int [] x = new int[0];
LinkedList<Integer> even = new LinkedList<Integer>(),
odd = new LinkedList<Integer>();
for(int num: x)
if (x & 1 == 1)
odd.add(num);
else
even.add(num);
The other option is to iterate through, counting how many evens and odds there are, allocating arrays of the correct size, and then putting the numbers into the arrays. That is also an O(n) solution.
Upvotes: 0
Reputation: 1289
I would not use three arrays to do this. Simply traverse through the list and have two loop variables that reference the even and odd indexes.Something like this:
int evenIndex=0,oddIndex=1;
int evenSum=0,OddSum=0;
int [] x=new int[10];
while(evenIndex <= x.length && oddIndex <= x.length)
{
evenSum+=x[evenIndex];
oddSum+=x[oddIndex];
evenIndex+=2;
oddIndex+=2
}
Upvotes: 0
Reputation: 2104
You aren't using arrays correctly. I'm assuming this is homework designed to teach you how to use them. Try this tutorial:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Good luck!
Upvotes: 2
Reputation: 362187
Arrays are fixed size in Java. They don't grow dynamically. Use an ArrayList
if you want an array-like container that can grow and shrink.
List<Integer> even = new ArrayList<Integer>();
List<Integer> odd = new ArrayList<Integer>();
if (...)
{
even.add(number);
}
else
{
odd.add(number);
}
Upvotes: 2