0

I get an error when i try to input name and num in a loop,

int i = 1;
    while(i <3) {
        System.out.print("Please enter name: ");
        String name = input.nextLine();
        
        System.out.print("Please enter number: ");
        int num = input.nextInt();
        i++;
    }

The error that i am getting is this

enter image description here

on the first iteration the input is normal, however on the second iteration it prints the enter num and name at the same line. Could anyone explain to me why is this happening?

BradLee
  • 31
  • 5
  • 2
    `input.nextInt()` doesn't consume the newline after the number, causing the next call to `nextLine()` to consume just that character immediately. Add a `input.nextLine()` call right after `nextInt()` to fix it. – marstran Aug 19 '21 at 11:56
  • 1
    Next time, please provide your input / output and your exception stacktrace as text with your question, not as an image. See [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551) – maloomeister Aug 19 '21 at 12:02
  • @maloomeister understood, sorry I am still new to stack overflow – BradLee Aug 19 '21 at 12:04

2 Answers2

1

when calling nextInt() you only read the integer, but there is a new line character that should also be read. so at the end of the loop, call input.nextLine() to read the new line.. and then the rest of the loop should work fine.

maha
  • 643
  • 5
  • 20
1

https://stackoverflow.com/a/26626204/14951486

Already answered

Refer the link

Error because you are taking String input after int