In the following Java code
Scanner input = new Scanner(System.in); //Cmd1
int i1,i2; //Cmd2
i1 = input.nextInt(); //Cmd3
System.out.println("value of i1 is "+ i1); //Cmd4
i2 = input.nextInt(); //Cmd5
System.out.println("value of i2 is "+ i2); //Cmd6
String s1; //Cmd7
input.nextLine(); //Cmd8
s1 = input.nextLine(); //Cmd9
System.out.println("value of s1 is "+ s1); //Cmd10
I got the following output in my console
<myinput> 1
<output> value of i1 is 1
<myinput> 2
<output> value of i2 is 2
<myinput> firstString
<output> value of s1 is firstString
<myinput> kept on waiting for input till i pressed enter
key. I tried tab
, multiple tab
, space
but it kept on waiting and didn't move to the next command which is <output> hence i assumed that nextInt waits till it find \n in an input stream before moving onto next command.
Looking at the answers from Scanner is skipping nextLine() after using next() or nextFoo()?, the reason we have to add Cmd8
is because nextInt() keep on reading input till \n
, sends input to program and puts \n
back in front of input stream. Now when nextLine() in "Cmd8" starts reading it, it finds \n
at the starting of input stream without any preceding string, it assumes user didn't enter anything hence takes empty string as input and go to Cmd9
.
My doubt here is since nextInt() also reads till \n
(implying from my experience that Cmd3
kept on waiting until i pressed enter
) why is Cmd5
waiting for my input. It should have also find \n
in the beginning of input stream and assume that i didn't enter anything and take empty integer as input (similar to how Cmd8
is behaving). What is happening here?