有關java裡,nextLine()無法輸入的問題

來源:互聯網
上載者:User

標籤: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()無法輸入的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.