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.