Java的。输入带偶数的任何奇数时程序崩溃

时间:2013-12-16 14:59:33

标签: java arrays if-statement methods

该程序用于计算用户输入的偶数。但是,当用户输入偶数和奇数时,程序崩溃。但是当用户输入所有奇数或甚至程序工作正常。我似乎无法找到错误,因为错误消息返回:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at AllEven.getEven(AllEven.java:52)
    at AllEven.read(AllEven.java:41)
    at AllEven.main(AllEven.java:10)
Java Result: 1

该计划的代码如下,任何帮助将不胜感激

import java.util.Scanner;
public class AllEven 
{
private static int evenCount;
private static int[] evenArray;
private static int count;

public static void main (String args [])
{
    read();//LINE 10
}

public static int [] read ()
{
    Scanner scanner = new Scanner (System.in);

    System.out.println("Please enter the size of the array");
    int arrayIn = scanner.nextInt();

    if (arrayIn == 0)
    {
        System.out.println("No Array");
    }
    else
    {
        System.out.println("------------------");
    }

    int userArray [] = new int [arrayIn];

    for (int i = 0; i < userArray.length;  i++)
    {
        System.out.println("Please enter a value for position: " + i);
        arrayIn = scanner.nextInt();
        userArray[i] = arrayIn;
        if (arrayIn % 2 == 0)
        {
           evenCount++;
        }
    }
            getEven(userArray);//LINE 41
    return userArray;   
}

public static int [] getEven(int[] userArray)
{
   if (evenCount > 0)
    {
        evenArray = new int [evenCount];
        for (int i = 0; i < userArray.length; i++)
        {
            evenArray[count] = userArray[i]; //LINE 52
            count++;
        }
        print (evenArray);
    }
    else
    {
        System.out.println("No even numbers found");
    }
    return evenArray;
}

public static void print (int [] evenArray)
{

    System.out.println();
    System.out.println("Even numbers in the array are: ");
    for (int i = 0; i < evenArray.length; i++)
    {
        System.out.println(evenArray[i]);
    }
}

}//endprogram

2 个答案:

答案 0 :(得分:6)

userArray.length 始终等于evenCount

有问题的代码

    evenArray = new int [evenCount];
    for (int i = 0; i < userArray.length; i++)
    {
        evenArray[count] = userArray[i];

答案 1 :(得分:0)

您的偶数小于用户数组的大小,但您正在索引到偶数数组count次。每次从输入数组中获取项目时,您都在递增计数,如果同时输入偶数和奇数,则输入数组将始终大于偶数数组。