Dalton Craig Dalton Craig - 1 month ago 6
Java Question

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. 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.

Answer

All you need to do is

if (voltage < 0 || voltage > 20) {
    System.out.println("Invalid input.");
    break;
}