Scanner輸入的一些問題和解決方法

1.下面兩段程序,第二段有問題,為什么第一段沒問題?
Scanner sc = new Scanner(System.in);
System.out.println("請輸入第一個字符串:");
String str1 = sc.nextLine();
System.out.println("請輸入第二個字符串:");
String str2 = sc.nextLine();
System.out.println("str1 = "+ str1 +"," + "str2 = "+ str2);

            Scanner sc = new Scanner(System.in);
    System.out.println("請輸入第一個數(shù)字:");
    int num1 = sc.nextInt();
    System.out.println("請輸入第一個字符串:");
    String str3 = sc.nextLine();
    System.out.println("num1 = "+ num1 +"," + "str3 = "+ str3);
            原因:因為nextLine();輸入字符串時,遇到\r\n,就會結(jié)束讀取,但是不讀取\r\n。在第二段程序中,輸入一個數(shù)字后按回車,數(shù)字賦值給num1后nextInt()讀取結(jié)束。后邊nextLine();遇到回車(\r\n)也就結(jié)束讀取。怎樣解決?

常用方法:輸入都使用.nextLine();后邊使用方法使字符串轉(zhuǎn)數(shù)字,如下:
Scanner sc = new Scanner(System.in);
System.out.println("請輸入第一個數(shù)字:");
String str1 = sc.nextLine();
int num1 = Integer.parseInt(str1);
System.out.println("請輸入第一個字符串:");
String str2 = sc.nextLine();

    System.out.println("num1 = "+ num1 +"," + "str2 = "+ str2);

2.在使用Scanner輸入整數(shù)時可以使用,一個方法先判斷是否輸入是整數(shù):
Scanner sc = new Scanner(System.in);
int num = 0;
System.out.println("請輸入整數(shù):");
if(sc.hasNextInt()){
num = sc.nextInt();
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容