简体   繁体   中英

Java. Program crashes when entering any odd number with even numbers

The program is meant to count how many even numbers that have been inputted by the user. However, when the user inputs even numbers along with odd numbers the program crashes. But when the user enters all odd or even the program works fine. I can't seem to find the error either as the error message returns:

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

The code for the program is below and any help would be greatly appreciated

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

userArray.length is not always equal to evenCount

problematic code

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

Your even count is less than the size of the user array, yet you are indexing into the even array count times. You are incrementing count each time you get an item from the input array, and the input array will always be larger than the even array if you enter both even and odd numbers.

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