简体   繁体   English

将偶数和奇数整数添加到数组中

[英]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. 我似乎无法在if循环中将整数添加到数组中。

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. 数组在Java中是固定大小的。 They don't grow dynamically. 它们不会动态增长。 Use an ArrayList if you want an array-like container that can grow and shrink. 如果您想要一个可以增长和缩小的类似数组的容器,请使用ArrayList

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 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. 这也是O(n)解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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