Java do while Loop not continuing



如果接收到无效输入,则重复执行我的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();
}

}

Scanner file = new Scanner(new File("list.csv"));放入do while循环将是一个不错的尝试

您的do-while循环完全正确,但问题是,如果输入和第一个字母不匹配,则您的循环为not updating f

因此,如果您希望用户只输入一次,或者创建另一个布尔值或使用值为0、1或2的整数变量,则不必执行while循环,而只需向用户请求输入一次。

最新更新