0

I'm trying to fill a string array with values through user input. I'll be doing more with this class later, but just want to see the array filled and print it out. I'm using a while loop to fill to a specific value, waiting for the user to enter 0 to stop, but I get an ArrayIndexOutOfBoundsException no matter the size of my array or for loops after I submit one value. Entering 0 also doesn't stop it. Full code below.

Also, the exception has the size of my array associated with it (in this case, 25.)

Help would be very appreciated-thanks!

import java.util.Scanner;

public class Dincision {
static Scanner scanner = new Scanner(System.in);

public static String entered;
public static String[]foods;

public static void main (String[]args){
    getChoices();
    int count=0;
    for (count=0; count<=24; count++){
        System.out.println(foods[count]);
    }
}

static public void getChoices() {
    int i=0;
    foods= new String[25];
    String input;
    System.out.println("Enter an eating option.");
    input=scanner.next();
    while (input != "0"){
        foods[i]=input; //error here//
        i++;
    }
    System.out.println("That's all!");

}
}
Jerevand
  • 9
  • 3

2 Answers2

0

You should limit your looping in the while statement to the size of the array. You try to get food[26] which does not exist.

Stimpson Cat
  • 1,444
  • 19
  • 44
0

Since I can't comment: I prefer

!"0".equals(input)

because it works when input is null.