Question

In: Computer Science

A question about exceptions, the language is JAVA. The purpose is writing a program that reads...

A question about exceptions, the language is JAVA.

The purpose is writing a program that reads a string from the keyboard and tests whether it contains a valid time.
Display the time as described below if it is valid, otherwise display a message as described below.
The input date should have the format hh:mm:ss (where hh = hour, mm = minutes and ss =
seconds in a 24 hour clock , for example 23:47:55).
Here are the input errors (Exceptions) that your program should detect and deal with:
Receive the input from the user ( give an example of the format you are expecting the user to use
when entering the time ) and check for the following:
a. missing one of parts (the hour or the minutes or the second is missing.
b. hh, mm or ss is not numeric
c. hh not between 0 and 23
d. mm is not between 0 and 59
e. ss is not between 0 and 59

Be specific when reporting an error. For example, “The input 24:04:20 contains an invalid hour
of 24”.
If the user gives you invalid input, start the whole process again by asking the user for a valid
time. Keep prompting the user until you get a valid time. A while (!valid) loop would work well
here.
If the time is valid, then output a message in this format, “23:45:16 is 11:45:16 pm”. That is,
convert it to the am/pm format.

The program should be coded as a series of method calls (within the try block, inside the while loop):
1. getInput( ) – asks the user for the time. Uses the String split( ) method to break it into 3 parts.
Checks that there are 3 parts and throws a MissingColonException if there aren’t. The method
returns the String array.
2. checkHour( ) – receives the hour String part of the array, tries to convert it to a numeric value, then
checks if the number is between 0 and 23. Throws NumberFormatException and HourException
3. checkMinutes( ) – similar to checkHour( )
4. checkSeconds( ) – similar to checkHour( )

Notes:
1. Be sure that the output that you submit shows that your program has tested ALL the
different types of errors that can occur.
2. The messages output by the catch blocks should be very specific. For example, output “24 is an
invalid hour”, or “23:15 is missing one part”, rather than simply “invalid hour” or “invalid input”.
The first 2 messages allow the user to better understand what input caused the problem; the other
messages leave the user guessing about what the source of the problem is.
3. You do not need to write code for the NumberFormatException class; this already exists as
part of Java.
4. You’ll need to write class definition files for the other exceptions described above.

Solutions

Expert Solution

import java.util.*;
public class ValidTime
{
   //method to get input
   public static String[] getInput()
   {
       //prompt the user to enter an input
       System.out.print("Enter valid time:\t");
       Scanner sc = new Scanner(System.in);
       String time = sc.nextLine();
       //split the input
       String[] vals = time.split(":");
       return vals;
   }
   //method to check the hours are valid or not
   public static int checkHours(String time, String hour) throws Exception
   {
       //conver the string to integer
       int hours = Integer.parseInt(hour);
       //check whether the hours are in given range
       if(hours < 0 || hours > 23)
       {
           throw new HourException(time, hour);
       }
       return hours;
   }
   //method to check the minutes are valid or not
   public static int checkMinutes(String time, String minute) throws Exception
   {
       //conver the stirng to integer
       int minutes = Integer.parseInt(minute);
       //check whether the minutes are in given range
       if(minutes < 0 || minutes > 59)
       {
           throw new MinuteException(time, minute);
       }
       return minutes;
   }
   //method to chcek the seconds are valid or not
   public static int checkSeconds(String time, String second) throws Exception
   {
       //conver the string to integer
       int seconds = Integer.parseInt(second);
       //check the seconds are in given range
       if(seconds < 0 || seconds > 59)
       {
           throw new SecondException(time, second);
       }
       return seconds;
   }
   public static void main(String args[]) throws Exception
   {
       //iterate in an infinite loop
       while(true)
       {
           //call the method to get input
           String[] vals = getInput();
           String time = vals[0] + ":" + vals[1] + ":" + vals[2];
           try
           {
               //call the three functions
               int hours = checkHours(time, vals[0]);
               int minutes = checkMinutes(time, vals[1]);
               int seconds = checkSeconds(time, vals[2]);
               //if all are valid calculate the time in 12 hour format and print the output
               if(hours >= 12)
               {
                   hours = hours - 12;
                   if(hours == 0)
                   {
                       hours = 12;
                   }
                   System.out.println(time + " is " + hours + ":" + minutes + ":" + seconds + " pm");
                   break;
               }
               else if(hours == 0)
               {
                   hours = 12;
                   System.out.println(time + " is " + hours + ":" + minutes + ":" + seconds + " am");
                   break;
               }
               else
               {
                   System.out.println(time + " is " + hours + ":" + minutes + ":" + seconds + " am");
                   break;
               }
           }
           //catch the appropriate exception and print the output
           catch(NumberFormatException e)
           {
               System.out.println("Invalid Format");
           }
           catch(HourException e)
           {
               e.toString();
           }
           catch(MinuteException e)
           {
               e.toString();
           }
           catch(SecondException e)
           {
               e.toString();
           }
       }
      
   }
}
//class for hour exception
class HourException extends Exception
{
   //define the constructor to print the message
   HourException(String time, String hour)
   {
       System.out.println("The input " + time + " consists an invalid hour of " + hour);
   }
}
//class for minute exception
class MinuteException extends Exception
{
   //define the constructor to print the message
   MinuteException(String time, String minutes)
   {
       System.out.println("The input " + time + " consists an invalid minute of " + minutes);
   }
}
//class for second exception
class SecondException extends Exception
{
   //define the constructor to print the message
   SecondException(String time, String seconds)
   {
       System.out.println("The input " + time + " consists an invalid second of " + seconds);
   }
}

If you have any doubts please comment and please don't dislike.


Related Solutions

Programing Language: Java The Problem: You are writing a program that encrypts or decrypts messages using...
Programing Language: Java The Problem: You are writing a program that encrypts or decrypts messages using a simple substitution cipher. Your program will use two constant strings. One will represent the code for encryption: going from the original message (called the plaintext) to the encrypted version of the message. The other will be “abcdefghijklmnopqrstuvwxyz” (the lowercase alphabet. Your program will ask the user whether they want to 1) encrypt a message, 2) decrypt a message, or 3) quit. If they...
Write a program in Java that reads a file containing data about the changing popularity of...
Write a program in Java that reads a file containing data about the changing popularity of various baby names over time and displays the data about a particular name. Each line of the file stores a name followed by integers representing the name’s popularity in each decade: 1900, 1910, 1920, and so on. The rankings range from 1 (most popular) to 1000 (least popular), or 0 for a name that was less popular than the 1000th name. A sample file...
In this question, you are asked to write a simple java program to understand natural language....
In this question, you are asked to write a simple java program to understand natural language. The user will enter the input following the format: Name came to City, Country in Year. For example: Robin came to Montreal, Canada in 2009. Assume a perfect user will follow the exactly above formats for the inputs. Your program should be able to analyze the key words (Name, City, Country and Year) from the inputs and reorganize the outputs following format: Name stay...
Write a Java program that reads a list of integers into an array. The program should...
Write a Java program that reads a list of integers into an array. The program should read this array from the file “input.txt”. You may assume that there are fewer than 50 entries in the array. Your program determines how many entries there are. The output is a two-column list. The first column is the list of the distinct array elements; the second column is the number of occurrences of each element. The list should be sorted on entries in...
IN C LANGUAGE This program reads a threshold, a size, and an array of integers. The...
IN C LANGUAGE This program reads a threshold, a size, and an array of integers. The program then calls the foo function. The function will modify the array x of size n by doubling any values in x that are less than the threshold. The function will count how many values were changed and how many were not changed via two reference parameters. The function signature is: void foo(int n, int x[], int threshold, int *pChanged, int *pUnchanged); The function...
What is the java root class for exceptions? java.lang.throw java.lang.exceptions java.lang.errors java.lang.Throwable Which statement about exceptions...
What is the java root class for exceptions? java.lang.throw java.lang.exceptions java.lang.errors java.lang.Throwable Which statement about exceptions is NOT true. Exception handling enables a program to deal with errors during execution. Exceptions are compile time errors. Exceptions are thrown from a method. An exception is an Exceptions can be primitives or objects. True False "try-with-resources" syntax is used to ___________________. automatically close the files used in the program. throw an exception for a memory related error. all of the above validate...
programing language JAVA: Design and implement an application that reads a sentence from the user, then...
programing language JAVA: Design and implement an application that reads a sentence from the user, then counts all the vowels(a, e, i, o, u) in the entire sentence, and prints the number of vowels in the sentence. vowels may be upercase
Bank Accounts in Java! Design and implement a Java program that does the following: 1) reads...
Bank Accounts in Java! Design and implement a Java program that does the following: 1) reads in the principle 2) reads in additional money deposited each year (treat this as a constant) 3) reads in years to grow, and 4) reads in interest rate And then finally prints out how much money they would have each year. See below for formatting. Enter the principle: XX Enter the annual addition: XX Enter the number of years to grow: XX Enter the...
*Java program* Use while loop 1.) Write a program that reads an integer, and then prints...
*Java program* Use while loop 1.) Write a program that reads an integer, and then prints the sum of the even and odd integers. 2.) Write program to calculate the sum of the following series where in is input by user. (1/1 + 1/2 + 1/3 +..... 1/n)
***Please answer the question using the JAVA programming language. Write a program that calculates mileage reimbursement...
***Please answer the question using the JAVA programming language. Write a program that calculates mileage reimbursement for a salesperson at a rate of $0.35 per mile. Your program should interact (ask the user to enter the data) with the user in this manner: MILEAGE REIMBURSEMENT CALCULATOR Enter beginning odometer reading > 13505.2 Enter ending odometer reading > 13810.6 You traveled 305.4 miles. At $0.35 per mile, your reimbursement is $106.89. ** Extra credit 6 points: Format the answer (2 points),...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT