The goal is to make code that can handle exceptions and keep going. I made a try/catch for typing string instead of numbers, but when I test it, it prints the catch output but then has these errors :
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at Paint1.main(Paint1.java:31)
I cant figure out where I went wrong. Please help, thank you.
import java.util.Scanner;
import java.util.InputMismatchException;
public class Paint1 {
public static void main(String[] args){
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
try {
do {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <=0) {
System.out.println("Invalid: Height must be more than 0. Try again.");
continue;
}
}while(wallHeight <=0);
}catch(InputMismatchException e){
System.out.println("Invalid: not a number. Try again.");
wallHeight = scnr.nextDouble();
}
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's width
try {
do {
System.out.println("Enter wall width (feet): ");
wallWidth = scnr.nextDouble();
if (wallWidth <=0) {
System.out.println("Invalid: Width must be more than 0. Try again.");
continue;
}
}while(wallWidth <= 0);
}catch(InputMismatchException e){
System.out.println("Invalid: not a number. Try again.");
wallWidth = scnr.nextDouble();
}
scnr.close();
// 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");
}
}