如果收到無效輸入,我的 do while 回圈會重復。但是它不會接受有效的輸入。我哪里錯了?
所以我從檔案中讀取一行中的第一個字符,然后將其與用戶輸入進行匹配。如果用戶輸入匹配,則此方法有效。如果用戶輸入不匹配,它會卡在回圈中,再次要求輸入。它應該做什么,但也應該接受一旦輸入有效輸入然后結束。
公開課測驗{
public static void selection() throws FileNotFoundException {
boolean f = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("Make booking:");
Scanner file = new Scanner(new File("list.csv"));
do {
System.out.print(" Select the car number from the car list: ");
char input = keyboard.next().charAt(0);
String storeInput = "";
while (file.hasNextLine()) {
storeInput = file.nextLine();
String finalInput = storeInput;
if (storeInput.charAt(0) == input) {
finalInput = finalInput (" is the booking ");
System.out.println(finalInput);
f = true;
}
}
if (!f) {
System.out.println("Invalid car selection");
}
} while (!f);
}
public static void main(String[] args) throws FileNotFoundException {
selection();
}
}
uj5u.com熱心網友回復:
把Scanner file = new Scanner(new File("list.csv"));進入do-while回圈將是一個很好的嘗試
uj5u.com熱心網友回復:
您的 do while 回圈完全正確,但問題是not updating f如果輸入和第一個字母不匹配,則您的回圈是正確的。
因此,如果您希望它成為另一個布林值或使用值為 0、1 或 2 的整數變數,而不是執行 while 回圈,只需要求用戶輸入一次即可。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351219.html
