我無法連續接收 2 個用戶輸入。當我運行下面的代碼時,它不會注冊第二行。如果我收到它,因為int a = Integer.valueof(reader.nextLine());它給出了一個錯誤。
基本上它會跳過第二個輸入。如果我println在 2 個輸入之間放置,則沒有問題,但此代碼適用于其他 IDE。
IntelliJ 有問題還是我做錯了什么?
Scanner reader = new Scanner(System.in);
System.out.println("Input two strings");
String a = reader.nextLine();
String b = reader.nextLine();
System.out.println("you wrote " a " " b);
代碼為整數:

錯誤:

uj5u.com熱心網友回復:
正如該nextLine()方法的檔案所述
將此掃描器前進到當前行并回傳被跳過的輸入。此方法回傳當前行的其余部分,不包括末尾的任何行分隔符。[...]
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()
按回車鍵對應輸入兩個字符:換行符(\n)和回車符(\r)。這兩個都是行分隔符。當您鍵入第一個輸入然后按 Enter 時,Scanner回傳第一行,停止然后等待第二個輸入(您的第二次nextLine()呼叫)。但是,由于已經有一個行終止符(前一次讀取的第二個行終止符),一旦您輸入第二個輸入,您的掃描儀會立即在開頭停止并回傳一個空的String.
您需要做的是擺脫nextLine()在第一次和第二次讀取之間放置的“額外”行終止符。
Scanner reader = new Scanner(System.in);
System.out.println("Input two strings");
String a = reader.nextLine();
reader.nextLine();
String b = reader.nextLine();
System.out.println("you wrote " a " " b);
或者,您可以使用兩條列印訊息請求輸入。事實上,第二次列印會向前移動Scanner的內部游標(因為程式已經在螢屏上寫了一些文本),跳過第二行終止符并正確檢索您的輸入:
Scanner reader = new Scanner(System.in);
System.out.println("Input the first string");
String a = reader.nextLine();
System.out.println("Input the second string");
String b = reader.nextLine();
System.out.println("you wrote " a " " b);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/474898.html
標籤:爪哇 输入 jetbrains-ide
