Question

I am required to use the try - catch block to validate the input as the...

I am required to use the try - catch block to validate the input as the test data uses a word "Thirty" and not numbers. The program needs to validate that input, throw an exception and then display the error message. If I don't use the try - catch method I end up with program crashing. My issue is that I can't get the try - catch portion to work. Can you please help? I have attached what I have so far. The last time I asked this question they ignored the try - catch piece and just reposted my code. It is important that the try - catch piece works and this is the second time I have had to ask the same question.

Thanks,

Overview

Many Java programs that you create will receive and process user input. In order to ensure that user input is accurate, you will need to use input validation and exception handling. For example, if you ask for a zip code, you want to ensure the user inputs a five-digit number. In this activity, you are given “buggy” code for a paint program that calculates the number of cans of paint required to paint a wall, given the wall’s height and width. You will need to debug the code and improve it by adding code to validate user input and handle exceptions.

Prompt

For this assignment, you will complete the paint program by debugging the original code and adding code that validates user input and handles exceptions. Use the Uploading Files to Eclipse and the Downloading Files from Eclipse Tutorial tutorials to help you with this project.

  • Debugging
    • Open the Virtual Lab by clicking on the link in the Virtual Lab Access module. Then open your IDE. Upload the Paint1.zip folder and review the code for the Paint1.java file.
    • Find and fix the three errors in the given code.
    • Use the input values below to test your program. If you found and fixed all errors, your output should exactly match what is below.
      TIP: When you run your program in Eclipse, it will prompt you to enter input in the Console window. If you cannot find this window, go to Window, then Show View, then Console.

Input value table with the numerals 30 and 25

Output value table with the wall area as 750.0 square feet and the paint needed as 2.142857142857143 gallons

  • Input Validation and Exception Handling
    • Review the code, looking for the two code blocks where user input is required.
    • Implement a do-while loop in both blocks of code to ensure that input is valid and any exceptions are handled.
      TIP: Consider using a try-catch block for exception handling, but it is not required.
    • Use the two sample invalid inputs below to test your program. Your program should respond to each by prompting the user to enter valid input. This should continue to loop until valid input is received.

A table with two columns titled Input 1 and Input 2. The items under Input 1 are the spelled-out number thirty and the numeral 25. The items under Input 2 are the numerals 30 and 0.

THINK: Why is 0 invalid input for this problem? What is the user being asked to input?

This is what I have so far but I can't get the try, throw and catch to work. Can you please help?

import java.util.Scanner;

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/While loop examples in 3.18 of Zybooks
      
        do {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        } while ((wallHeight <= 0));
      

        // Implement a do-while loop to ensure input is valid
        // Prompt user to input wall's width
      
        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 0
Add a comment Improve this question Transcribed image text
Answer #1

The modified program

import java.util.Scanner;

public class Main {

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/While loop examples in 3.18 of Zybooks
  
do {
System.out.println("Enter wall height (feet): ");
try{
wallHeight = scnr.nextDouble();
} catch(Exception e) {
System.out.println("Please enter wall height in number format");
scnr.next(); // absorb the enter key to avoid the infinite loop.
}
} while ((wallHeight <= 0));
  

// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's width
  
do {
System.out.println("Enter wall width (feet): ");
try {
wallWidth = scnr.nextDouble();
}catch(Exception e) {
System.out.println("Please enter wall width in number format ");
scnr.next(); // absorb the enter key to avoid the infinite loop.
}
} 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");

}
}

the sample output:

42 Enter wall height (feet): thirty Please enter wall height in number format Enter wall height (feet): 30 Enter wall width (

Add a comment
Know the answer?
Add Answer to:
I am required to use the try - catch block to validate the input as the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • For practice using exceptions, this exercise will use a try/catch block to validate integer input from...

    For practice using exceptions, this exercise will use a try/catch block to validate integer input from a user. Write a brief program to test the user input. Use a try/catch block, request user entry of an integer, use Scanner to read the input, throw an InputMismatchException if the input is not valid, and display "This is an invalid entry, please enter an integer" when an exception is thrown. InputMismatchException is one of the existing Java exceptions thrown by the Scanner...

  • This Exercise contains two classes: ValidateTest and Validate. The Validate class uses try-catch and Regex expressions...

    This Exercise contains two classes: ValidateTest and Validate. The Validate class uses try-catch and Regex expressions in methods to test data passed to it from the ValidateTest program. Please watch the related videos listed in Canvas and finish creating the 3 remaining methods in the class. The regular expression you will need for a Phone number is: "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$" and for an SSN: "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$" This exercise is meant to be done with the video listed in the...

  • IT Java code In Lab 8, we are going to re-write Lab 3 and add code...

    IT Java code In Lab 8, we are going to re-write Lab 3 and add code to validate user input. The Body Mass Index (BMI) is a calculation used to categorize whether a person’s weight is at a healthy level for a given height. The formula is as follows:                 bmi = kilograms / (meters2)                 where kilograms = person’s weight in kilograms, meters = person’s height in meters BMI is then categorized as follows: Classification BMI Range Underweight Less...

  • Compute for Miles Per Gallon in C++

    Make a program that will calculate and compute for the quotient of miles and gallons (mpg: miles per gallons). Your program should must ask the user to specify the size of the array (using dynamic array) for the following variable: miles ,gallons and mpg. Prompt the user to Initialize  the value of miles (value for miles should be 100-250) and gallons (values should be from 5-25). Use pointer galPtr for gallons, milPtr for miles and mpgPtr for mpg.  Use function...

  • (1) Prompt the user to input a wall's height and width. Calculate and output the wall's...

    (1) Prompt the user to input a wall's height and width. Calculate and output the wall's area. (Submit for 2 points). Enter wall height (feet): 12 Enter wall width (feet): 15 Wall area: 180 square feet (2) Extend to also calculate and output the amount of paint in gallons needed to paint the wall. Assume a gallon of paint covers 350 square feet. Store this value using a const double variable. (Submit for 2 points, so 4 points total). Enter...

  • Lesson is about Input validation, throwing exceptions, overriding toString Here is what I am supposed to...

    Lesson is about Input validation, throwing exceptions, overriding toString Here is what I am supposed to do in the JAVA Language: Model your code from the Time Class Case Study in Chapter 8 of Java How to Program, Late Objects (11th Edition) by Dietel (except the displayTime method and the toUniversalString method). Use a default constructor. The set method will validate that the hourly employee’s rate of pay is not less than $15.00/hour and not greater than $30.00 and validate...

  • I am getting an error from eclipse stating that: Exception in thread "main" java.lang.Error: Unresolved compilation...

    I am getting an error from eclipse stating that: Exception in thread "main" java.lang.Error: Unresolved compilation problem: at EvenOdd.main(EvenOdd.java:10) I am unable to find what I can do to fix this issue. Can you please assist? My code is below: import java.util.InputMismatchException; import java.util.Scanner; public class EvenOdd {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);        System.out.println("Welcome to this Odd program!");        int userInput1 = input.nextInt();    }       public...

  • How would I try/catch recovery from a format mismatch error? The scanner needs to continue prompting...

    How would I try/catch recovery from a format mismatch error? The scanner needs to continue prompting until the user enters a valid number. I know that I would need to try n = kbd.nextInt(); and catch a InputMismatchException and if n<1 or n>100 then I need to print Out of Range Exception. Must be in 1..100. However, I am unsure how to loop all of that. import java.io.*; import java.util.*; public class Lab5 { public static void main( String args[]...

  • import java.util.Scanner; import java.io.File; public class Exception2 {        public static void main(String[] args) {              ...

    import java.util.Scanner; import java.io.File; public class Exception2 {        public static void main(String[] args) {               int total = 0;               int num = 0;               File myFile = null;               Scanner inputFile = null;               myFile = new File("inFile.txt");               inputFile = new Scanner(myFile);               while (inputFile.hasNext()) {                      num = inputFile.nextInt();                      total += num;               }               System.out.println("The total value is " + total);        } } /* In the first program, the Scanner may throw an...

  • 12p I need help this is Python EXCEPTIONS: It's easier to ask forgiveness than permission. Try...

    12p I need help this is Python EXCEPTIONS: It's easier to ask forgiveness than permission. Try the code and catch the errors. The other paradigm is 'Look before you leap' which means test conditions to avoid errors. This can cause race conditions. 1.Write the output of the code here: class MyError(Exception): pass def notZero(num): if num == 0: raise MyError def run(f): try: exec(f) except TypeError: print("Wrong type, Programmer error") except ValueError: print("We value only integers.") except Zero Division Error:...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT