Scanner類nextInt方法的使用注意點


一、先看一段正常的代碼

1. 一段用Scanner捕獲鍵盤輸入的代碼:

Scanner sc = new Scanner(System.in);
// 先讀取鍵盤輸入的字符串
System.out.println("input name :");
String name = sc.nextLine();
// 后讀取鍵盤輸入的int值
System.out.println("input id :");
int id = sc.nextInt();

System.out.println("id = " + id + " name =[" + name + "]");
System.out.println("execute finish !");

2. 測試結果

2.1 運行程序

input name :
lings //鍵盤輸入
input id :
0 //鍵盤輸入

2.2 程序輸出

id = 0 name =[lings]
execute finish !

和預期一樣。

 

二、一個小變化,顛倒一下取值類型的順序

1. 一段改變了取值順序的代碼:

Scanner sc = new Scanner(System.in);

// 先讀取鍵盤輸入的int值
System.out.println("input id :");
int id = sc.nextInt();

// 后讀取鍵盤輸入的字符串
System.out.println("input name :");
String name = sc.nextLine();

System.out.println("id = " + id + " name =[" + name + "]");
System.out.println("execute finish !");

2. 測試結果

2.1 運行程序

input id :
0 //鍵盤輸入
input name :

2.2 程序輸出

id = 0 name =[]
execute finish !

咦?說好的阻塞呢?我還沒輸入字符串怎么就執行結束了???

3. 原因如下:

nextInt方法根據分隔符(回車,空格等)只取出輸入的流中分割的第一部分並解析成Int,然后把后面的字節傳遞下去。
所以,第二種情況鍵盤實際輸入是“0+回車”,nextInt讀出了“0”,並留下了“回車”,
接着netxLine讀到了一個“回車”,這是字符串的結束判定符啊,所以讀到的字符串就是空字符串“”。

4. 有點暈?繼續測試:

4.1 運行程序

input id :
0 lings //鍵盤輸入
input name :
4.2 程序輸出

id = 0 name =[ lings] //注意空格
execute finish !

這下清楚了嗎?

三、使用注意事項

需要從鍵盤輸入多個參數,盡量把nextLine類型放前面,nextInt放后面,實在不行。

nextInt后面要跟一個nextLine方法“消化”掉那個多余的字符串。

1. 消化掉多余字符串的例子

Scanner sc = new Scanner(System.in);

System.out.println("input id :");
int id = sc.nextInt();
sc.nextLine();
System.out.println("input name :");
String name = sc.nextLine();

System.out.println("id = " + id + " name =[" + name + "]");
System.out.println("execute finish !");

2. 測試結果

2.1 運行程序
input id :
0
input name :
lings

2.2 程序輸出

id = 0 name =[lings]
execute finish !

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM