Java 在循环不继续时执行
Java do while Loop not continuing
如果收到无效输入,我的 do while 循环会重复。
但是它不会接受有效的输入。
我哪里错了?
所以我正在从文件中读取一行中的第一个字符,然后将其与用户输入进行匹配。
如果用户输入匹配,这有效。
如果用户输入不匹配,它就会陷入循环,再次请求输入。
它应该做什么,但也应该在输入有效输入后接受然后结束。
publicclass测试{
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();
}
}
您的 while 循环完全正确,但问题是如果输入和第一个字母不匹配,您的 not updating f
。
因此,与其执行 while 循环,不如只询问用户一次输入(如果您希望如此),或者创建另一个布尔值或使用值为 0、1 或 2 的整数变量。
将 Scanner file = new Scanner(new File("list.csv"));
放入 do-while 循环将是一个很好的尝试
如果收到无效输入,我的 do while 循环会重复。 但是它不会接受有效的输入。 我哪里错了?
所以我正在从文件中读取一行中的第一个字符,然后将其与用户输入进行匹配。 如果用户输入匹配,这有效。 如果用户输入不匹配,它就会陷入循环,再次请求输入。 它应该做什么,但也应该在输入有效输入后接受然后结束。
publicclass测试{
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();
}
}
您的 while 循环完全正确,但问题是如果输入和第一个字母不匹配,您的 not updating f
。
因此,与其执行 while 循环,不如只询问用户一次输入(如果您希望如此),或者创建另一个布尔值或使用值为 0、1 或 2 的整数变量。
将 Scanner file = new Scanner(new File("list.csv"));
放入 do-while 循环将是一个很好的尝试