我昨天剛開始學習Java,今天我在學習輸入法。我知道為什么我們需要在使用.nextLine()after using獲取輸入之前清除掃描儀緩沖區.nextInt(),但我注意到如果我在從.nextLine(). 我不得不使用.nextLine()兩次而不是一次來洗掉緩沖區,否則它無法按預期作業。
我最初的代碼是這樣的:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number :");
int num = sc.nextInt();
sc.nextLine();
System.out.println("Enter the string :");
String str = sc.nextLine();
System.out.println(num);
System.out.println(str);
因此,如果我在獲取輸入字串并將其存盤在 variable 之前洗掉了 print 陳述句,即使我之前洗掉了緩沖區str,它也會再次將值傳遞給該變數。\n.nextLine()
當前代碼:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number :");
int num = sc.nextInt();
sc.nextLine();
sc.nextLine();
String str = sc.nextLine();
System.out.println(num);
System.out.println(str);
理想情況下,列印陳述句不應該對掃描儀緩沖區產生任何影響,對吧?那么,為什么要跳過它呢?
另外,既然我已經洗掉了緩沖區,那么為什么它再次將值傳遞\n給我的變數str,除非我兩次洗掉緩沖區或在輸入之前傳遞列印陳述句。
我嘗試用谷歌搜索它,并嘗試在 YouTube 和此處進行大量搜索,但沒有一個解決方案真正討論了我現在面臨的這個問題。
uj5u.com熱心網友回復:
這完全是一個解釋錯誤,是在輸入程序中造成的。
在運行代碼時,您可以在自己喜歡的 IDE 中運行它。根據游標在控制臺上的位置,你們中的一個人(您或 IDE)無意中在末尾添加了另一個 '\n' 字符。這會導致掃描儀將其讀取為另一行。您也可以通過鍵盤上的箭頭鍵(上、下、左、右)移動游標。
好的,但為什么System.out.println();解決問題?
因為它將游標移動到正確的位置。
使用不同的 IDE,你會發現這個問題不會發生。
uj5u.com熱心網友回復:
這不是列印陳述句或“緩沖區”的問題。
你看,nextInt()方法留下了一個換行符,即 \n 在輸入中懸空。
因此,即將到來的nextLine()方法選擇這個 \n 作為輸入,因此,您必須添加另一個 nextLine() 來捕獲實際的字串輸入。
解決方案:
改為
使用Integer.parseInt(sc.nextLine())獲取 int 值并使用 normalsc.nextLine()獲取字串輸入。
或者在 nextLine() 之前添加 nextLine() 以消耗這個額外的 \n 以獲取實際輸入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474722.html
標籤:爪哇 缓冲 java.util.scanner 下一个
上一篇:獲取/搜索陣列
下一篇:AWSLambdajava.lang.ClassNotFoundException:com.opencsv.exceptions.CsvException
