简体   繁体   中英

Adding even and odd integers into Array

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++;
        }

}

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);
}

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!

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 

            }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM