Write a program the prompts the user to enter a length in feet and inches and outputs the equivalent length in centimeters.If the user enters a negative number or a nondigit number, throw and handle an appropriate exception and prompt the user to enter another set of numbers.

Respuesta :

Answer:

The solution is written in Java.

  1. public class Main {
  2.    public static void main(String[] args) {
  3.        double CM_PER_INCH = 2.54;
  4.        double CM_PER_FOOT = 30.48;
  5.        double feet = 0;
  6.        double inches = 0;
  7.        double centimeter;
  8.        Scanner input = new Scanner(System.in);
  9.        try{
  10.            System.out.print("Please enter feet: ");
  11.            String input_feet = input.nextLine();
  12.            feet = Double.parseDouble(input_feet);
  13.            System.out.print("Please enter inch: ");
  14.            String input_inches = input.nextLine();
  15.            inches = Double.parseDouble(input_inches);
  16.            if(feet >= 0 && inches >=0){
  17.                centimeter = feet * CM_PER_FOOT + inches * CM_PER_INCH;
  18.                System.out.println("The total centimeter is " + centimeter);
  19.            }else{
  20.                throw new IllegalArgumentException();
  21.            }
  22.        }
  23.        catch(NumberFormatException ex){
  24.            System.out.println("The input must be digit.");
  25.            System.out.println("Please re-enter input.");
  26.        }
  27.        catch(IllegalArgumentException e){
  28.            System.out.println("The input must be positive number.");
  29.            System.out.println("Please re-enter input.");
  30.        }
  31.    }
  32. }

Explanation:

There are two types of errors required to captured: Negative value error and non-digit error.

Hence, we can define two error handling blocks as in (Line 25-28 and Line 29 - 32) to handle those two errors, respectively.

To check for non-digit error, we can use parseDouble method (Line 13 & 16). If the input is not a digit, the exception, NumberFormatException will be raised. If the input is negative value, IllegalArgumentException will be raised.

If everything goes smooth, the program will calculate the centimeter and display it to terminal (Line 19-20).