JAVA 从不同数组填充数组时出现程序错误

JAVA program bug when populating array from different array

当从 inputList 填充 oddList、evenList 和 negativeList 时,程序只用一个 int 填充它,而不是 inputList 数组中的所有对应的 int。输出应该是每个数组的列表,其数字对应于它的标题。用户将数字输入到 inputList 数组中,然后从那里确定它是奇数、偶数和负数,然后填充相应的数组。 IE。 evenList 由 inputList 中的偶数整数填充。

public class ProjectTenOne {

public static void main(String[] args)
{
    int[] inputList = new int[10];
    int[] oddList = null;
    int[] evenList = null;
    int[] negativeList = null;
    int evenCount = 0;
    int oddCount  = 0;
    int negCount  = 0;


    Scanner input = new Scanner(System.in);

    //System.out.println("Enter any ten integers: ");

    for(int list = 0; list < inputList.length; list++)
    {
        System.out.println("Enter any " + (inputList.length - list) +  " integers: ");
        inputList[list] = input.nextInt();

    }
    System.out.println();
    System.out.println("The numbers you entered: ");

    for(int in = 0; in < inputList.length; in++)
    {
        System.out.println(inputList[in]);
    }


    for(int ls = 0; ls< inputList.length; ls++)
    {
        if(inputList[ls] % 2 == 0)
        {
            evenCount = evenCount +1;
        }
        if(inputList[ls] % 2 != 0)
        {
            oddCount = oddCount +1;
        }
        if(inputList[ls] < 0)
        {
            negCount = negCount +1;
        }
    }

    evenList     = new int[evenCount];
    oddList      = new int[oddCount];
    negativeList = new int[negCount];

    for(int l = 0; l < inputList.length; l++)
    {
        if((inputList[l] % 2) == 0)
        {   
            for(int j = 0; j < evenList.length; j++)
            {
                evenList[j] = inputList[l];

            }
        }
        if((inputList[l] % 2) != 0)
        {
            for(int k = 0; k < oddList.length; k++)
            {
                oddList[k] = inputList[l];

            }
        }
        if(inputList[l] < 0)
        {
            for(int h = 0; h < negativeList.length; h++)
            {
                negativeList[h] = inputList[l];

            }
        }
    }

    System.out.println("The ODD List is: ");
    for(int i = 0; i < oddList.length; i++)
    {
        System.out.println(oddList[i]);
    }

    System.out.println("The EVEN List is: ");
    for(int j = 0; j < evenList.length; j++)
    {
        System.out.println(evenList[j]);
    }

    System.out.println("The NEGATIVE List is: ");
    for(int k = 0; k < oddList.length; k++)
    {
        System.out.println(negativeList[k]);
    }
}

}

这里以evenList为例,其他两个数组也一样。

在您的代码中,您遍历 inputList 并检查偶数。如果是偶数,则将整个 evenList 数组设置为找到的值,而不仅仅是单个元素。

您可以通过在外循环之外声明一个 int 来解决这个问题,该 int 用于跟踪输入的偶数的数量。例如:

int evenIndex = 0;
for(int l = 0; l < inputList.length; l++)
{
    if((inputList[l] % 2) == 0)
    {
        evenList[evenIndex++] = inputList[l];
    }
    /*Other code*/
}

你在上一个循环中也犯了一个错误。你遍历了 negativeList,但是你使用了 evenList 的大小。当 negativeList 小于 evenList 时,这将导致 ArrayIndexOutOfBoundsException。