You\'ve created an application named quartstogallonsinteractive that accepts a n
ID: 3677367 • Letter: Y
Question
You've created an application named quartstogallonsinteractive that accepts a number of quarts from a user and converts the value to gallons. Now, add an exception-handling capabilities to this program and continuously reprompt the user while any nonnumeric value is entered. Save the file as QuartsToGallonsWithExceptionHandling.java
What I have will compile with no errors but doesn't do anything to prompt user for values.
import java.util.Scanner;
class QuartsToGallonsInteractiveExceptionHandling
{
public static void main(String[] args)
{
// Set your variables
Scanner input = new Scanner(System.in);
final int> int quarts;
boolean isGoodUserEntry = true;
while(!isGoodUserEntry)
{
System.out.println("Enter number of quarts");
try{
quarts = Integer.parseInt(input.nextLine());
int gallons = quarts / oneQuart;
quarts = quarts % oneQuart;
System.out.println("A job that needs " + gallons + " gallons plus " +
quarts + " quarts.");
isGoodUserEntry = false;
}
// Catch the exception if it's not good
catch(Exception e){
System.out.println("Exception: " + " NumberFormatException");
}
}
}
}
Explanation / Answer
import java.util.Scanner;
class QuartsToGallonsInteractiveExceptionHandling
{
public static void main(String []args){
// Set your variables
int num;
System.out.println("Enter number of quarts");
Scanner input = new Scanner(System.in);
num = input.nextInt();
final int> int quarts;
boolean isGoodUserEntry = true;
while(!isGoodUserEntry)
{
try{
quarts = Integer.parseInt(input.nextLine());
int gallons = quarts / oneQuart;
quarts = quarts % oneQuart;
System.out.println("A job that needs " + gallons + " gallons plus " +
quarts + " quarts.");
isGoodUserEntry = false;
}
// Catch the exception if it's not good
catch(Exception e){
System.out.println("Exception: " + " NumberFormatException");
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.