0

i don't understand why i am getting the output for next element when the program is terminated by the loop condition. if i input 3 the program terminates asking for the 3rd value but didn't input anything. what's the problem

    Scanner in = new Scanner(System.in);
    System.out.println("number of word you want to input");
    int NumberOfWord = in.nextInt();
   System.out.println("input the words-->");
    for (int i = 0; i <= NumberOfWord; i++) {
        userInput[i] = in.nextLine();
        System.out.println("enter your "+(i+1)+"th word");

1 Answers1

1

When you are using the in.nextInt() it only reads the integer value from the input stream. But it won't read the newline character that comes after that.

What you can do is use a dummy in.nextLine() before calling the nextLine() method in your loop which is used to read the newline character that comes after the integer value.

int NumberOfWord = in.nextInt();
in.nextLine();
System.out.println("input the words-->");
for (int i = 0; i < NumberOfWord; i++) {
   userInput[i] = in.nextLine();
   System.out.println("enter your " + (i + 1) + "th word");
}

Another solution is to use the nextLine() method itself to read the integer value also. The nextLine() method reads an entire line from the stream with the newline character as the termination point(includes the newline character also). So it takes care of the issue that was happening while using the nextInt()

int NumberOfWord = Integer.parseInt(in.nextLine());
System.out.println("input the words-->");
for (int i = 0; i < NumberOfWord; i++) {
    userInput[i] = in.nextLine();
    System.out.println("enter your " + (i + 1) + "th word");
}

Also in your loop condition you where using <= which will ask for one more value as your loop is starting from 0

Johny
  • 2,003
  • 3
  • 17
  • 31