The Java Scanner is not taking my String Input
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
Here is my code. It is compiled properly and no syntax error but I can't understand why my String input is not taken. As soon as I give the integer input and the double input, the output is coming as:
INPUT
42
309.23
OUTPUT
String:
Double: 309.23
Int: 42
Solution 1:
Note that for the single line input 1 1.1 done
you shall get the output:
String: done
Double: 1.1
Int: 1
That done
is preceded in the output by a space character hints to you that scanner is consuming one token at a time. Checkout for example the documentation for scan.nextInt and scan.nextLine
Solution 2:
scan.nextDouble()
or scan.nextInt()
doesn't finish the line so when scan.nextLine()
comes simple you can say that it consume the leftover blank line so the String prints nothing. To consume the leftover line put scan.nextLine()
before String s = scan.nextLine();