2012-10-12 81 views
1

可能重複:
Scanner issue when using nextLine after nextIntnextLine方法在掃描儀

爲什麼丈夫下的空sc.nextLine();所以有必要嗎?它並不等於任何東西,當然妻子也沒有這一行......但是如果沒有它,程序就不會運行。我的書評論它跳過結尾newLine字符。但我看不出有什麼可跳過的!

public class FileTest { 
    public static void main(String[] args) { 

    Scanner sc = new Scanner(System.in); 
    System.out.print("For your blended family, \n enter the wife's name"); 
    String wife = sc.nextLine(); 
    System.out.print("Enter the number of her children:"); 
    int herkids = sc.nextInt(); 

    System.out.print("Enter the husband's name:"); 
    //sc.nextLine(); // Why is this line so necessary? 
    String husband = sc.nextLine(); 
    System.out.print("Enter the number of his children:"); 
    int hisKids = sc.nextInt(); 

    System.out.println(wife + " and " + husband + " have " + (herkids + hisKids) + " children."); 

    } 
} 
+0

@JohnWatts確定,同意... – user133466

回答

6

檢查這個問題,

Scanner issue when using nextLine after nextXXX

看接受的答案,

「問題與input.nextInt()命令時,它只能讀取int值。因此,當你繼續用input.nextLine()讀取時,你會收到「\ n」回車鍵,所以要跳過這個,你必須添加input.nextLine(),希望現在應該清楚。

+0

這應該是關閉作爲一個完全重複的 – RonK

+0

我看,這是否意味着nextLine()命令消耗字符串和\ n? – user133466

+0

@ user133466從我的理解,這將是正確的。 – Austin