2

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.

4
  • You've got two input = kbReader.nextLine() in your loop. That doesn't make sense!!! You should probably take the first one outside (before the beginning of) the loop. Alternatively, you can place the exit-condition immediately after the first input-scan, and get rid of the second input-scan. Commented Nov 20, 2014 at 18:38
  • 4
    Use a break keyword. Commented Nov 20, 2014 at 18:38
  • Looks like you should replace 'System.out.println("invalid input");' with 'break;' Commented Nov 20, 2014 at 18:41
  • @AndyFedoroff only quotes should be in quotes, reverting your changes Commented Oct 15, 2016 at 8:31

3 Answers 3

1

All you need to do is

if (voltage < 0 || voltage > 20) {
    System.out.println("Invalid input.");
    break;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a break in that first if clause :

if (voltage < 0 || voltage > 20)
{
  break;
}

Comments

0

You can try using a break;. Breaks allows the while loop to exit.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.