1
public class Array {

  public static void main ( String[] args ) {


    int DAYS_SIZE = 5;
    double[] sales = new double[DAYS_SIZE];

    String input;
    char userResponse;
    Scanner keyboard = new Scanner(System.in);

    double total = 0;
    double average = 0;
    int index = 0;

    do {
        index++;
        System.out.print("Enter sales for day " + index  + ": ");
        sales[index] = keyboard.nextInt();             

        System.out.print("Another ( y or n )? " );
        input = keyboard.next();
        userResponse = input.charAt(0);

     } while ( userResponse == 'Y' || userResponse == 'y');   

  }
}

I keep getting java.lang.ArrayIndexOutOfBoundsException: 5 at the last day

I know why this is happening but i dont know how to solve it

1 Answer 1

1

you increase your index before you access the array without checking whether the index is already bigger than the size of the array. When the user enters days and days index will become bigger than 5 in your case.

Also as the index starts with 0 and not with 1, there is no index 5, but only 0-4

Sign up to request clarification or add additional context in comments.

4 Comments

Should i add a decision structure that checks whether if the index is bigger than the size of the array, or is there a better way?
Why do you need to increment index straight away? Just move it to the bottom of your iteration.
i put it at the bottom and i still get java.lang.ArrayIndexOutOfBoundsException: when i input the sales for the last day which would be 5.
because you never check whether the index is bigger than the size of the array. You can either add the index < sales.length check in your while condition or separately if you like to give the user an extra message like "no more days left" or so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.