import java.util.Scanner; public class Main { public static void main(String[] args) { int s1; String s2; Scanner sc = new Scanner(System.in); System.out.print("請輸入第一個數:"); s1 = sc.nextInt(); System.out.print("請輸入第二個字符串:"); s2 = sc.nextLine(); System.out.println("輸入的值為:" + s1 + " " + s2); sc.close(); } }
nextInt()一定要讀取到有效字符后才可以結束輸入,對輸入有效字符之前遇到的空格鍵、Tab鍵或Enter鍵等結束符,nextInt()方法會自動將其去掉,只有在輸入有效字符之后,nextInt()方法才將其后輸入的空格鍵、Tab鍵或Enter鍵等視為分隔符或結束符。簡單地說,nextInt()查找並返回來自此掃描器的下一個完整標記。完整標記的前后是與分隔模式匹配的輸入信息,所以next方法不能得到帶空格的字符串。
而nextLine()方法的結束符只是Enter鍵,即nextLine()方法返回的是Enter鍵之前的所有字符,它是可以得到帶空格的字符串的。
可以看到,nextLine()自動讀取了被nextInt()去掉的Enter作為他的結束符,所以沒辦法給s2從鍵盤輸入值。經過驗證,我發現其他的next的方法,如double nextDouble() , float nextFloat() , int nextInt() 等與nextLine()連用時都存在這個問題,解決的辦法是:在每一個 next()、nextDouble() 、 nextFloat()、nextInt() 等語句之后加一個nextLine()語句,將被next()去掉的Enter結束符過濾掉。