I have the following code call it code#1
Scanner keyboard = new Scanner(System.in);
String s = keyboard.nextLine();
int x = keyboard.nextInt();
double y = keyboard.nextDouble();
System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
If I enter
Hello World
12.1
12
The output will be
String: Hello World
Double: 12.1
Int: 12
However, If I rearrange my code, call it code#2, as
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
double y = keyboard.nextDouble();
String s = keyboard.nextLine();
System.out.println("String: "+s);
System.out.println("Double: "+y);
System.out.println("Int: "+x);
and I enter
12
12.1
the compiler skips the string input and outputs
String:
Double: 12.1
Int: 12
This is odd to me. I was taught compilers always read from top to bottom. I imagine the compiler reads code#2 as
int x = keyboard.nextInt();
first and waits for the user to enter an integer so it can assign it to x. Then reads
double y = keyboard.nextDouble();
waiting for the user to enter a double so it can be assigned to y. It then finally reads
String s = keyboard.nextLine();
and waits for the user to enter a string so it can assign it to s. In fact, to me, this how the compiler read code#1 and the output is desired. This seems like a subtle difference, rearranging the variables, but then why are the outputs so different?