我正在做这个程序,它会无限地询问汽车的型号,直到用户输入0来中断循环。当我运行它并输入一个数字时,它会无限循环,要么你的车是有缺陷的,要么直到它崩溃才是有缺陷的。我现在被困住了,任何帮助都将不胜感激。
Scanner input = new Scanner(System.in);
System.out.print("Enter a model number or 0 to quit: ");
modelNum = input.nextInt();
while (modelNum != 0) {
if (modelNum >= 189 && modelNum <= 195) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 189 || modelNum == 221) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 780) {
System.out.println("Your car is defective it must be repaired");
} else if (modelNum == 119 || modelNum == 179) {
System.out.println("Your car is defective it must be repaired");
} else {
System.out.println("Your car is not defective");
}
if (modelNum == 0) {
System.out.println("end");
break;
}
}
发布于 2018-01-10 20:37:54
这是因为您从未要求用户提供其他输入。您应该在循环结束之前执行此操作。
发布于 2018-01-10 20:38:34
将this部分包含到您的循环中:
Scanner input = new Scanner(System.in);
System.out.print("Enter a model number or 0 to quit: ");
modelNum = input.nextInt();
发布于 2018-01-10 20:49:11
您必须请求一个要评估的新值:
while (modelNum != 0) {
// if conditions
modelNum = input.nextInt();
}
另请注意:
if (modelNum == 0) {
System.out.println("end");
break;
}
这是不必要的,因为如果最后一个值为0
,则while循环中的条件将为false,并且不会再次循环。
最后一件事:为什么你会有所有的if-else-if,当它们都做同样的事情时(打印“你的车有缺陷,它必须修理”)。这就足够了:
while (modelNum != 0) {
if ((modelNum >= 189 && modelNum <= 195) || modelNum == 221 || modelNum == 780 || modelNum == 119 || modelNum == 179) {
System.out.println("Your car is defective it must be repaired");
} else {
System.out.println("Your car is not defective");
}
modelNum = input.nextInt();
}
https://stackoverflow.com/questions/48195629
复制