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");

    }
}
ernest_k
  • 39,584
  • 5
  • 45
  • 86
Chris
  • 13
  • 5

1 Answers1

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.

luckydog32
  • 909
  • 6
  • 13
  • 1
    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 Dec 09 '19 at 05:38
  • @Chris No problem my dude. Good luck with the rest of your project! – luckydog32 Dec 09 '19 at 05:40