I just started learning Java yesterday, and today I was learning input-taking. I got to know why we need to clear the scanner buffer before taking input using .nextLine()
after using .nextInt()
, but I noticed one thing if I remove the print statement just before taking the input from .nextLine()
. I had to use .nextLine()
twice instead of once to remove the buffer otherwise it was not working as intended.
My initial code was this:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number :");
int num = sc.nextInt();
sc.nextLine();
System.out.println("Enter the string :");
String str = sc.nextLine();
System.out.println(num);
System.out.println(str);
So, if I remove the print statement just before taking the input string and storing it in variable str
, it was again passing the value \n
to that variable even though I removed the buffer using .nextLine()
earlier.
Current code:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number :");
int num = sc.nextInt();
sc.nextLine();
sc.nextLine();
String str = sc.nextLine();
System.out.println(num);
System.out.println(str);
Ideally, the print statement shouldn't have any effect on the scanner buffer, right? So, why is it skipping it?
Also, since I have already removed the buffer, then why it is again passing the value \n
to my variable str
unless I either remove the buffer two times or pass the print statement before taking the input.
I tried googling it, and tried searching it a lot on YouTube and here as well, but none of the solutions actually discussed this issue which I am facing right now.
This is completely an interpretation error, made during giving the input.
While you are running your code, you run it in your favorite IDE. One of you (you or the IDE) unintentionally adds another '\n' char to the end according to your cursor's place on the console. This causes the scanner to read that as another line. You can move your cursor by arrow keys (up,down,left,right) on your keyboard as well.
Okay, but why System.out.println();
solves the problem?
Because it moves your cursor to the right place.
Use a different IDE and you'll see that this problem will not happen.