sc.next() 和 nextLine 的區別

來源:互聯網
上載者:User

next()一定要讀取到有效字元後才可以結束輸入,對輸入有效字元之前遇到的空格鍵、Tab鍵或Enter鍵等結束符,next()方法會自動將其去掉,只有在輸入有效字元之後,next()方法才將其後輸入的空格鍵、Tab鍵或Enter鍵等視為分隔字元或結束符。簡單地說,next()尋找並返回來自此掃描器的下一個完整標記。完整標記的前後是與分隔模式比對的輸入資訊,所以next方法不能得到帶空格的字串。

而nextLine()方法的結束符只是Enter鍵,即nextLine()方法返回的是Enter鍵之前的所有字元,它是可以得到帶空格的字串的。

鑒於以上兩種方法的只要區別,同學們一定要注意next()方法和nextLine(0方法的連用,下面舉個例子來說明:

 

import java.util.Scanner;public class Next {public static void main(String[] args) {String s1, s2;Scanner sc = new Scanner(System.in);System.out.println("請輸入第一個字串:");s1 = sc.nextLine();System.out.println("請輸入第二個字串:");s2 = sc.next();System.out.println("輸入的字串是:" + s1 + "  " + s2);}}

運行結果

請輸入第一個字串:
ss
請輸入第二個字串:
dd
輸入的字串是:ss  dd

 

但如果把程式改一下, s1=sc.next(); s2=sc.nextLine();

import java.util.Scanner;public class Next {public static void main(String[] args) {String s1, s2;Scanner sc = new Scanner(System.in);System.out.println("請輸入第一個字串:");s1 = sc.next();System.out.println("請輸入第二個字串:");s2 = sc.nextLine();System.out.println("輸入的字串是:" + s1 + "  " + s2);}}

運行結果

請輸入第一個字串:
ss
請輸入第二個字串:
輸入的字串是:ss 

可以看到,nextLine()自動讀取了被next()去掉的Enter作為他的結束符,所以沒辦法給s2從鍵盤輸入值。經過驗證,我發現其他的next的方法,如double nextDouble()  , float nextFloat() , int nextInt() 等與nextLine()連用時都存在這個問題,解決的辦法是:在每一個 next()、nextDouble()  、 nextFloat()、nextInt() 等語句之後加一個nextLine()語句,將被next()去掉的Enter結束符過濾掉。例如上面的程式改寫為:

 

import java.util.*;public class Next {public static void main(String[] args) {Scanner sc=new Scanner(System.in);System.out.println("請輸入第一個字串");String s1=sc.next();sc.nextLine();System.out.println("請輸入第二個字串");String s2=sc.nextLine();System.out.println("輸入的字串是"+s1+" "+s2);}}

 

 

聯繫我們

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