關於Scanner鍵盤接收方法中scan.nextLine()和scan.nextInt()的區別

來源:互聯網
上載者:User
 

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();

因為行裡面已經沒有資料了,所以程式會阻塞,一直到你再輸入資料為止。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.