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); }}
以下是我的理解是,哪裡不對還請大家指正:
String s = sc.nextLine();
這裡讀到的是一個Null 字元串。
因為你在輸入完第二個數字以後,按了一下斷行符號。
假設你第二個數字輸入的是:5(加一個斷行符號)
則程式實際收到的是:5/r/n
nextInt() 掃描到了5
nextLine();繼續掃描,這個方法會返回當前行的剩餘部分,(一直到遇到行分隔字元為止,而且不包括行分隔字元)
因為5的後面是一個行分隔字元/r ,所以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); }}
這個代碼可以運行成功,是因為sc.nextLine() 會將讀取到的行分隔字元自動去掉。
所以你在輸入第二個數位時候:5(加一個斷行符號)
輸入的是5/r/n
不過程式實際掃描到的是5
當再執行這句代碼的時候:
-
Java code
-
String s = sc.nextLine();
因為行裡面已經沒有資料了,所以程式會阻塞,一直到你再輸入資料為止。