我是第一次学习java的初学程序员。我无法弄清楚如何让程序重复,直到用户输入0。 这是问题所在: 应用程序应允许用户根据需要输入尽可能多的型号。使用0作为最终用户输入的标记。
输入汽车的型号或0以退出:195 你的车有缺陷。它必须得到修复。 输入汽车的型号或0以退出:119 你的车有缺陷。它必须得到修复。 输入汽车的型号或0以退出:0
public class CarRecall
{
// Main method
public static void main(String[] args)
{
int model; //model number
Scanner input = new Scanner(System.in);
do
{
System.out.print("Enter the car's model number or 0 to quit: ");
model=input.nextInt();
input.close();
}
while (model>0);
{
if (model==119)
{
System.out.print("Your car is defective. It must be repaired.");
}
else if (model==179)
{
System.out.print("Your car is defective. It must be repaired.");
}
else if (model>=189 && model<=195)
{
System.out.print("Your car is defective. It must be repaired.");
}
else if (model==221)
{
System.out.print("Your car is defective. It must be repaired.");
}
else if (model==780)
{
System.out.print("Your car is defective. It must be repaired.");
}
else
System.out.print("Your car is not defective.");
model=0;
}
}
}
答案 0 :(得分:0)
如果您想使用while循环,在这种情况下看起来不太必要,请将Model
更改为0或添加break
while(Model>0){//add the brace
//...current if else code
Model = 0;//or simply break;
}
- 编辑 - (使用do while)
int Model; //model number
Scanner input = new Scanner(System.in);
do{
System.out.print("Enter the car's model number or 0 to quit: ");
Model=input.nextInt();
if (Model==119||Model==179||(Model>=189 && Model<=195)||Model==221||Model==780)
System.out.println("Your car is defective. It must be repaired.");
else if(Model>0)
System.out.println("Your car is not defective.");
}while(Model>0);
input.close();
答案 1 :(得分:0)
首先,似乎没有任何理由你应该使用循环。 elements[0].onmousedown = function(){
fireEvent(elements[0], 'onmouseup');
};
是一个数字,您可以对其进行检查,但这并不会更改变量function doSomethingOnMouseUp() {
console.log('something on mouse up');
}
elements[0].onmousedown = function(){
doSomething();
doSomethingOnMouseUp();
};
elements[0].onmouseup = doSomethingOnMouseUp;
的值。所以我建议删除整个循环。
如果你想对循环做一些事情,比如在某个时候调整变量model
(但还没有实现),你可以使用model
关键字来逃避您目前居住的循环:
model
答案 2 :(得分:0)
将代码更改为以下内容
while (true) {
System.out.print("Enter the car's model number or 0 to quit: ");
model=input.nextInt();
if (model == 0) {
break; // This will break you out of the loop
} else if (model == 119) {
System.out.print("Your car is defective. It must be repaired.");
} else if (model == 179) {
System.out.print("Your car is defective. It must be repaired.");
} else if (model >= 189 && model <= 195) {
System.out.print("Your car is defective. It must be repaired.");
} else if (model == 221) {
System.out.print("Your car is defective. It must be repaired.");
} else if (model == 780) {
System.out.print("Your car is defective. It must be repaired.");
} else
System.out.print("Your car is not defective.");
}
// Move the scanner close to outside the loop to avoid `IllegalStateException`.
input.close();
这将提示用户在每次迭代中输入一个新数字。当用户输入0时,它将转到相应的if
条件和break
循环。希望这会有所帮助。
为了让循环永远运行,我将while(model > 0)
更改为while(true)
。这将循环到无穷大,直到您输入&#39; 0&#39;。
注意:我还没有编译这段代码。只是摘录了你提出的问题。此外,我冒昧地将变量名称从Model
更改为model
。将变量名称从小写字母开始是一个好习惯。