[英]Java - How to quit a While Loop mid loop
I'm trying to make a program that asks an electrician to enter a number in Volts. 我正在尝试编写一个程序,要求电工输入伏特数。 If he/she enters a value either bigger than
20
or less than 0
, the program should end without prompting the user to go again. 如果他/她输入的值大于
20
或小于0
,则程序应结束而不提示用户再次输入。 Right now, I have it so it prompts the user to quit or continue, which I don't want. 现在,我有了它,因此它提示用户退出或继续,这是我不希望的。 Here's the guts of the program:
这是程序的胆量:
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
String input = "";
int voltage;
boolean Loop = true;
while (Loop) {
System.out.print("Enter a numeric value of 0 to 20 volts");
input = kbReader.nextLine();
voltage = Integer.parseInt(input);
if (voltage < 0 || voltage > 20) {
System.out.println("Invalid input.");
}
else if (voltage >= 0 && voltage < 5) {
System.out.println("Insufficient Voltage - Replace Relay");
}
else if (voltage >= 5 && voltage < 15) {
System.out.println("Low Voltage");
}
else if (voltage >= 15 && voltage < 18) {
System.out.println("Voltage is in proper range");
}
else if (voltage >= 18 && voltage <= 20) {
System.out.println("Voltage is high - Check Transformer");
}
System.out.print("\n\nType \"Q\" to quit, or type nothing to go again.");
input = kbReader.nextLine();
if (input.equalsIgnoreCase("q")) {
Loop = false;
}
}
}
The indentation seems to be a bit off. 缩进似乎有点偏离。 I'm not too sure how to fix that.
我不太确定该如何解决。
All you need to do is 您需要做的就是
if (voltage < 0 || voltage > 20) {
System.out.println("Invalid input.");
break;
}
You can use a break in that first if clause : 您可以在第一个if子句中使用break:
if (voltage < 0 || voltage > 20)
{
break;
}
You can try using a break;. 您可以尝试使用break;。 Breaks allows the while loop to exit.
中断允许while循环退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.