I have been learning Java for a little while and feel familiar with using a Scanner Object, but I came across some really confusing behavior.
If I print the result of the nextLine() method twice I get what you'd expect:
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine());
System.out.println(scan.nextLine());
Result (> denotes input):
> String 1
String 1
> String 2
String 2
But if I first set the result to a variable and then print it, I get that the second line is missed and I must invoke nextLine() a third time.
Scanner scan = new Scanner(System.in);
String scan1 = scan.nextLine();
String scan2 = scan.nextLine();
String scan3 = scan.nextLine();
System.out.println("scan1: " + scan1 + "\nscan2: " + scan2 + "\nscan3: " + scan3);
Result:
> String 1
> String 2
scan1: String 1
scan2:
scan3: String 2
I know that when invoking next() or nextInt() and similar methods, it doesn't actually read past the newline character and so when nextLine() is invoked, it reads the newline and ends immediately and then you have to invoke it again to read the whole next line. But this seems different, I mean nextLine() does read the newline character from what I understand, and the only thing I changed was assigning the result of the method to a variable.
I feel very stupid like I'm missing something right in front of me but if anyone knows why your help would be much appreciated. Thanks for reading.
Here is the full code also:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String scan1 = scan.nextLine();
String scan2 = scan.nextLine();
String scan3 = scan.nextLine();
System.out.println("scan1: " + scan1 + "\nscan2: " + scan2 + "\nscan3: " + scan3);
}
}