-1

I have encountered the same error many times, and I don't know why it happened or what caused it. I tried literally changing everything but it either only allows me to type 2 numbers or just gives me back the same error. What does this error even mean? How can I fix this? Any ideas? (I'm new to StackOverFlow) I'm trying to make this random element picker as you can see below:

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    System.out.println("Hi! Welcome to the random element picker! How many elements are you going to choose from?");
    Scanner input= new Scanner(System.in);
    int NumberOfElement= input.nextInt();
    String[] Elements= new String[NumberOfElement];
    System.out.println("type out all the elements! Press enter after each one!");
    for(int i=0;i<=NumberOfElement;i++){
        Elements[i]=input.nextLine();
    }
    int number = (int)(Math.random() * (NumberOfElement-1));
    System.out.println("I chose " + Elements[number]);
  }
}
  • 1
    `for(int i=0;i<=NumberOfElement;i++){` .. `0 .. <=` will go one past the end of the array. The axception will actually tell you that if you took the time to read it! – John3136 Feb 25 '20 at 00:29

1 Answers1

0

In loop you are having condition '<=' It should be '<' only. That is because array indexing starts from 0 (int i=0;i

  • Yes, I changed it to – Harry Peng Feb 25 '20 at 00:43
  • @HarryPeng See: [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/q/13102045/5221149) – Andreas Feb 25 '20 at 00:50
  • The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n. https://stackoverflow.com/questions/14452613/issues-with-nextline – Nitin Kolte Feb 25 '20 at 01:28