標籤:get system 去掉 oid inpu cores es2017 返回 code
在課後習題中用到了以下代碼
1 public static void main(String[] args) {2 System.out.print("輸入學生人數:");3 int student_number = input.nextInt();4 System.out.print("輸入學產生績:");5 String scores = input.nextLine();6 int[] score_arrayi = getScore(scores);7 int max_score = maxScore(score_arrayi);8 grade(score_arrayi,max_score);9 }
可是在具體輸入的時候會出現以下問題
也就是在輸入學生人數4之後,按下斷行符號。無法輸入學產生績,直接跳過
1 String scores = input.nextLine();
後來尋找資料後得知:
next()一定要讀取到有效字元後才可以結束輸入,對輸入有效字元之前遇到的空格鍵、Tab鍵或Enter鍵等結束符,next()方法會自動將其去掉,只有在輸入有效字元之後,next()方法才將其後輸入的空格鍵、Tab鍵或Enter鍵等視為分隔字元或結束符。簡單地說,next()尋找並返回來自此掃描器的下一個完整標記。完整標記的前後是與分隔模式比對的輸入資訊,所以next方法不能得到帶空格的字串
而nextLine()方法的結束符只是Enter鍵,即nextLine()方法返回的是Enter鍵之前的所有字元,它是可以得到帶空格的字串的。
意思就是說,nextInt()讀到有效值後就結束,輸完數字後按的斷行符號符還存在,nextLine()讀取到斷行符號符就直接結束,所以結果就類似於跳過了該條輸入語句
因此為瞭解決這個問題,可以在nextInt()後面再加上一個nextLine()完善代碼如下
1 public static void main(String[] args) { 2 System.out.print("輸入學生人數:"); 3 int student_number = input.nextInt(); 4 System.out.print("輸入學產生績:"); 5 input.nextLine(); 6 String scores = input.nextLine(); 7 int[] score_arrayi = getScore(scores); 8 int max_score = maxScore(score_arrayi); 9 grade(score_arrayi,max_score);10 }
有關java裡,nextLine()無法輸入的問題