0

I've been sitting here (embarrassingly) for hours trying to get a do-while loop to to accept user input until it's valid, but I seem to be messing up when it comes to the boolean that I'm using to try and exit the loop. Whenever I can get the program to partially work the catch exception just ends up repeating itself infinitely.

Scanner scnr = new Scanner(System.in);

double wallHeight = 0.0;
boolean valid = false;

// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        valid = false;

        if (wallHeight <=0) {
            throw new Exception ("Invalid Input");
        }
    }
    catch (Exception e) {
        System.out.println("Invalid Input");
    }
} while (!valid);
1
  • Also seem to have made the mistake when uploading the code of having the valid variable set to false twice. That was accidental. Commented Feb 17, 2020 at 4:16

3 Answers 3

1

Start by assuming the input is valid (and set valid to true on every iteration of the loop). Only set valid to false when you encounter an exception (hopefully the one you raised).

do {
    valid = true;
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        if (wallHeight <= 0) {
            throw new Exception("Invalid Input");
        }
    } catch (Exception e) {
        valid = false;
        System.out.println("Invalid Input");
    }
} while (!valid);

Note that you do not appear to need an exception here, as

do {
    valid = true;
    System.out.println("Enter wall height (feet): ");
    wallHeight = scnr.nextDouble();
    if (wallHeight <= 0) {
        System.out.println("Invalid Input");
        valid = false;
    }
} while (!valid);

would also work. Of course, that assumes the user only inputs valid double(s). If you need handle arbitrary input, you should check that there is a double before you attempt to consume it (and you must consume anything that isn't a double or you have an infinite loop). Like,

do {
    valid = true;
    System.out.println("Enter wall height (feet): ");
    if (scnr.hasNextDouble()) {
        wallHeight = scnr.nextDouble();
        if (wallHeight <= 0) {
            System.out.println("Invalid Input");
            valid = false;
        }
    } else {
        System.out.println("Invalid Input " + scnr.nextLine());
        valid = false;
    }
} while (!valid);
Sign up to request clarification or add additional context in comments.

5 Comments

I'm sorry maybe, I didn't describe the problem properly. But I want to exit the loop once valid input has been received and go back to the top of the loop when there has been invalid input.
@Bmore That is what this code does. valid should only be false when the loop should repeat. Thus you must set it to true at some point, or the loop will run forever.
Okay thank you very much. That's what I was having trouble with was dealing with alternative inputs. I thought that the try-catch would help with things like string inputs. Can they not work within a do-while loop or is scnr.hasNextDouble() absolutely necessary? Just so I know for the future.
It can, but you need scnr.nextLine() in the catch block (else nothing consumes the thing that caused the exception).
Happy to help. Welcome to Stack Overflow. Please take the tour.
0

Here is another take.I just moved the code that sets valid = true after the if check. It can make it that far only when its valid. Otherwise valid will be false and it will loop.

public class BasicDoWhile {

    public static void main(String[] args) {
        double wallHeight = 0.0;
        boolean valid = false;

        Scanner scnr = new Scanner(System.in);

        // Implement a do-while loop to ensure input is valid
        // Prompt user to input wall's height
        do {
            try {
                System.out.println("Enter wall height (feet): ");
                wallHeight = scnr.nextDouble();

                if (wallHeight <= 0) {
                    throw new Exception("Invalid Input");
                }

                valid = true;

            }
            catch (Exception e) {
                System.out.println("Invalid Input");
            }

        } while (!valid);

    }
}

Comments

0

Although I couldn't get the reason of the problem, i.e., the trap of infinite loop when the entered input is wrong(or, of undesired type). But, your problem can be solved by placing the instantiation of the Scanner() class inside the do {...} while (...) loop.

public static void main(String[] args) {

double wallHeight = 0.0;
boolean valid = false;

// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
  try {
    Scanner scnr = new Scanner(System.in);
    System.out.println("Enter wall height (feet): ");
    wallHeight = scnr.nextDouble();
    valid = true;
    
    scnr.close();
    if (wallHeight <=0) {
      throw new Exception ("Invalid Input");
    }
  }
  catch (Exception e) {
    System.out.println("Invalid Input");
  }
} while (!valid);

}

Also, close the Scanner object scnr in your program, like I did.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.