0

I have been working on this for hours and I just can't make sense of how to implement a try-catch in these two do while loops to catch if user enters a non-int. I know there are posts on this, but I can't seem to get it. I greatly appreciate any advice.

public class Paint {
    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        double wallHeight;
        double wallWidth;
        double wallArea = 0.0;
        double gallonsPaintNeeded = 0.0;
        final double squareFeetPerGallons = 350.0;

        // Implement a do-while loop to ensure input is valid
        // Handle exceptions(could use try-catch block)
        do {
            System.out.println("Enter wall height (feet): ");
            wallHeight = scnr.nextDouble();
        } while (!(wallHeight > 0));
        // Implement a do-while loop to ensure input is valid
        // Handle exceptions(could use try-catch block)
        do {
            System.out.println("Enter wall width (feet): ");
            wallWidth = scnr.nextDouble();
        } while (!(wallWidth > 0));

        // Calculate and output wall area
        wallArea = wallHeight * wallWidth;
        System.out.println("Wall area: " + wallArea + " square feet");

        // Calculate and output the amount of paint (in gallons) 
        // needed to paint the wall
        gallonsPaintNeeded = wallArea/squareFeetPerGallons;
        System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");

    }
}
0

1 Answer 1

3

First Initialize both wallHeight and wallWidth to a temporary value (we'll use 0) in the class:

double wallHeight = 0;
double wallWidth = 0;

Then you want to put scnr.nextDouble(); in the try block to catch a parse error:

do {
        System.out.println("Enter wall height (feet): ");
        try{
            wallHeight = scnr.nextDouble();
        }catch(InputMismatchException e){
            scnr.next(); //You need to consume the invalid token to avoid an infinite loop
            System.out.println("Input must be a double!");
        }
    } while (!(wallHeight > 0));

Note the scnr.next(); in the catch block. You need to do this to consume the invalid token. Otherwise it will never be removed from the buffer and scnr.nextDouble(); will keep trying to read it and throwing an exception immediately.

Sign up to request clarification or add additional context in comments.

2 Comments

That's exactly what was happening, I've been leaving scnr.nextDouble(); out this whole time. I can't believe this block of code had me so tripped up, I will definitely remember this. Thank you for the help!
@Chris No problem my dude. Good luck with the rest of your project!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.