繁体   English   中英

java中循环if和else语句

[英]Looping if and else statements in java

我正在研究这个程序,该程序无限地询问汽车的型号,直到该人输入 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;
    }
}

这是因为您从不要求用户提供其他输入。 您应该在循环结束之前这样做。

将此部分包含在您的循环中:

Scanner input = new Scanner(System.in);    

   System.out.print("Enter a model number or 0 to quit: ");
   modelNum = input.nextInt(); 

您必须要求评估一个新值:

while (modelNum != 0) {
    // if conditions
    modelNum = input.nextInt();
}

另请注意:

if (modelNum == 0) {
    System.out.println("end");
    break;
}

没有必要,因为如果最后一个值是0 ,while 循环中的条件将为假并且不会再次循环。

最后一件事:当它们都做同样的事情时,为什么你拥有所有这些 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();
}

如果输入 0,循环将中断,因此最后一个 if 语句将永远不会运行。

这个循环只是根据型号告诉你汽车是否有缺陷,但如果汽车有缺陷,你永远不会告诉程序退出循环。 为此,您必须将 break 语句放入循环的每个 if 语句中。

而且这个说法是没用的:

if(modelNum == 0) { System.out.println("end"); break;

因为如果你输入 0 循环不会开始。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM