Java code
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); String s = sc.nextLine(); System.out.print("a: " + a + " b: " + b + " s: " + s); }}
The following is my understanding. please correct me if there is anything wrong:
String S = SC. nextline ();
Here we read an empty string.
Because after entering the second number, you press Enter.
Assume that the second number you entered is: 5 (add a carriage return)
What the program actually receives is: 5/R/n
Nextint () scan to 5
Nextline (); Continue scanning. This method returns the remaining part of the current row until a line separator is encountered and does not include a line separator)
Because row separator/R is followed by row separator 5, only an empty string is scanned for nextline.
-
Java code
-
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = Integer.parseInt(sc.nextLine()); int b = Integer.parseInt(sc.nextLine()); String s = sc.nextLine(); System.out.print("a: " + a + " b: " + b + " s: " + s); }}
This code can run successfully because SC. nextline () will automatically remove the row separators read.
So when you enter the second number: 5 (add a carriage return)
5/R/n
However, the program actually scans 5
When executing the code again:
-
Java code
-
String s = sc.nextLine();
Because there is no data in the row, the program will be blocked until you enter the data again.