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");
}
}
CodePudding user response:
You had an order problem of your try catch and loop, plus you need to clear your scanner after to avoid cache problems
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
do {
try {
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;
}
} catch (InputMismatchException e) {
System.out.println("Invalid: not a number. Try again.");
scnr.nextLine();
}
} while (wallHeight <= 0);
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's width
do {
try {
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;
}
} catch (InputMismatchException e) {
System.out.println("Invalid: not a number. Try again.");
scnr.nextLine();
}
} while (wallWidth <= 0);
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");
}
}
CodePudding user response:
Now you know why your having problems but I just want to demonstrate another concept to carry out the same task without the need for try/catch
blocks. It involves using only the Scanner#nextLine() method along with the String#matches() method and a Regular Expression (regex).
Thing to note however, I have the belief that if you use the Scanner#nextLine() method for your Console application....then use it for everything. Don't mix next()
and nextFoo()
methods with it. Read the comments in code then delete them if you like.
Scanner scnr = new Scanner(System.in);
final String ls = System.lineSeparator();
/* A regular Expression that is used with the String#matches()
method that ensures either an unsigned integer or floating
point numerical string value has been supplied. */
final String dRegEx = "\\d (\\.\\d )?";
final double squareFeetPerGallons = 350.0d;
double wallHeight = 0.0d;
double wallWidth = 0.0d;
double wallArea = 0.0d;
double gallonsPaintNeeded = 0.0d;
/* Implement a do-while loop to ensure input is valid
Prompt user to input wall's height: */
System.out.println(" Paint Calculator");
System.out.println(" ================");
System.out.println("Enter wall height and width dimensions" ls
" or 'q' to quit at any time:" ls);
String wHeight = "";
while (wHeight.isEmpty()) {
System.out.print("Enter wall height (feet): -> ");
wHeight = scnr.nextLine().trim();
if (wHeight.equalsIgnoreCase("q")) {
System.out.print("Quiting..." ls);
return;
}
// Validate input...
if (!wHeight.matches(dRegEx)) {
System.out.println("Invalid measurement supplied! (" wHeight
") - Try again..." ls);
wHeight = ""; // empty so to re-loop
}
}
wallHeight = Double.parseDouble(wHeight);
// Prompt user to input wall's width
String wWidth = "";
while (wWidth.isEmpty()) {
System.out.print("Enter wall width (feet): -> ");
wWidth = scnr.nextLine().trim();
if (wWidth.equalsIgnoreCase("q")) {
System.out.print("Quiting..." ls);
return;
}
// Validate input...
if (!wWidth.matches(dRegEx)) {
System.out.println("Invalid measurement supplied! (" wWidth
") - Try again..." ls);
wWidth = ""; // empty so to re-loop
}
}
wallWidth = Double.parseDouble(wWidth);
/* In this use-case, don't close System.in unless you
know for sure that your application won't need it
again. If you do, you can't open it again unless
you restart your application. The JVM will handle
closing this resource when your application ends. */
// 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;
/* The String#format() method is used to display the amount of
gallons required to a few different decimal places. If the
wall Width OR the wall Height provided is greater than or equal
to 2 feet then a decimal precision of two is used. If the width
OR height is less than 2 and greater than or equal to 0.1 then
the decimal precision is five. If the the width or height is
less than 0.1 then the decimal precision will be seven. */
int precision = 2; // Default
if (wallWidth < 2 || wallHeight < 2) {
if (wallWidth < 0.1d || wallHeight < 0.1d) {
precision = 7;
}
else {
precision = 5;
}
}
System.out.println("Paint needed: " String.format("%-8." precision "f",
gallonsPaintNeeded).trim() " gallons" ls);