简体   繁体   中英

fixing Exception in main thread

Everything with my code seems to work correctly, whenever the boolean method returns true. However, when trying to test false, after the user enters 10 numbers I receive the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at FunArrays.main(FunArrays.java:15

What am I missing or overlooking with my code?

Here is my code:

import java.util.Scanner;

public class FunArrays {

public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.println("Please enter ten numbers....");

            int [] userArray = new int [9];

        for(int b = 0; b < 10 ; b++){
            userArray [b] = input.nextInt();
        }

            boolean lucky = isLucky(userArray);
                if (lucky){
                        sum(userArray);
    } else
        sumOfEvens(userArray);

}



public static boolean isLucky(int [] numbers){

    for (int i = 0; i <= numbers.length; i++){
        if (numbers[i]== 7 || numbers[i] == 13 || numbers[i] == 18){
            return true;

        }   

    }
    return false;

}



public static void sum(int [] numbers){
    int sum = 0;
    for (int x = 0; x <= numbers.length -1; x++){
        sum += numbers[x];

    }
    System.out.println(sum);
}

public static void sumOfEvens(int [] numbers){
    int evens = 0;
    for (int y = 0; y <= numbers.length -1; y++){
        if (numbers[y] % 2 == 0){
            evens += numbers[y];
        }
    }
    System.out.println(evens);
}

}

You are entering 10 numbers but your array has only 9 spots. Change it to

int [] userArray = new int [10];
 int [] userArray = new int [9];

    for(int b = 0; b < 10 ; b++){
        userArray [b] = input.nextInt();
    }

Your array size is 9 (from index 0 to index 8) and your loop increment b from 0 to 9 (10 cases) In this case b should be less than 9 in your loop.

So you could replace by this code:

int maxInput = 9;
int [] userArray = new int [maxInput];

    for(int b = 0; b < maxInput ; b++){
        userArray [b] = input.nextInt();
    }

You should declare a size 10 array, since you are accepting 10 values from the user.

int [] userArray = new int [9];

Here is a good read on Arrays: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Arrays/arrays.html

You're trying to store 10 numbers in an array of length 9.

Use int[] userArray = new int[10];

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