Concept explainers
Explanation of Solution
Creating “TimeOfDay.java”:
- Import required packages.
- Define the “TimeOfDay” class.
- Declare required variables.
- Define the constructor and instantiate the variables.
- Give function definition “setTimeTo ()” to set the time.
- Declare required variables.
- Create an object for the “Scanner” class.
- Split the string using a delimiter “:”.
- Inside the “try” block,
- Get the hour and store it in a variable.
- Catch the exception “Exception”.
- Throw the exception “InvalidFormattingException” with a message.
- Check if the hour value is valid.
- Throw “InvalidHourException” with a message.
- Get the remaining string and cut off the last two characters.
- Check if the string’s length is less than 3.
- Throw “InvalidFormattingException” with a message.
- Get the minutes and store it in a variable.
- Get “am” or “pm” and store it in a variable.
- Inside “try” block,
- Convert the minute string to integer.
- Catch the exception “Exception”.
- Throw “InvalidFormattingException” with a message.
- Check if minute is less than 0 or greater than 59.
- Throw “InvalidMinuteException” with a message.
- Check whether the string is not equal to “am” and “pm”.
- Throw “InvalidFormattingException” with a message.
- Check if the string is equal to “am”.
- Assign “true” to “isAM”.
- Else,
- Assign “false” to “isAM”.
- Function to produce the resultant string.
- Append all the value to a string.
- Define the “main ()” method.
- Create an object for the “Scanner” class.
- Create an object for the class “TimeOfDay”.
- Declare a variable “time”.
- Inside “try” block.
- Get the time from the user.
- Call the function “setTimeTo ()” by passing the time.
- Catch the exception “InvalidFormattingException”.
- Print the message using “getMessage ()” function.
- Catch the exception “InvalidHourException”.
- Print the message using “getMessage ()” function.
- Catch the exception “InvalidMinuteException”.
- Print the message using “getMessage ()” function.
- Print the time.
Creating “InvalidFormattingException.java”:
- Define a class “InvalidFormattingException” that extends “Exception”.
- Define a parameterized constructor.
- Call the parent class’s method using “super ()” by passing the message.
- Define a parameterized constructor.
Creating “InvalidHourException.java”:
- Define a class “InvalidHourException” that extends “InvalidFormattingException”.
- Define a parameterized constructor.
- Call the parent class’s method using “super ()” by passing the message.
- Define a parameterized constructor.
Creating “InvlaidMinuteException.java”:
- Define a class “InvalidMinuteException” that extends “InvalidFormattingException”.
- Define a parameterized constructor.
- Call the parent class’s method using “super ()” by passing the message.
- Define a parameterized constructor.
Program:
TimeOfDay.java:
//Import required packages
import java.util.*;
import java.util.Scanner;
//Define the main class
class TimeOfDay
{
//Declare required variables
private int hour, minute;
private boolean isAM;
//Constructor
public TimeOfDay()
{
//Instantiate the values
hour = 0;
minute = 0;
isAM = false;
}
//Function definition to set the time
public void setTimeTo(String aTime) throws InvalidFormattingException, InvalidHourException, InvalidMinuteException
{
//Declare required variables
int hourFound;
int minuteFound;
String indicatorFound;
//Create an object for the scanner class
Scanner reader = new Scanner(aTime);
//Split using the delimiter
reader.useDelimiter(":");
//Try block
try
{
//Assign the hour
hourFound = reader.nextInt();
}
//Catch the exception
catch (Exception e)
{
//Throw the exception with a message
throw new InvalidFormattingException("Hour not an integer");
}
//Check the condition
if(hourFound<1 || hourFound>12)
//Throw the exception with a message
throw new InvalidHourException("Hour not in the range of 1 to 12");
//Get the remaining string
String restOfString = reader.next();
reader = new Scanner(restOfString);
//Remove the last two characters
if(restOfString.length()<3)
//Throw the exception
throw new InvalidFormattingException("Bad format");
//Get the substring
String minuteString = restOfString.substring(0, restOfString.length()-2);
//Get the substring
String amString = restOfString.substring(restOfString.length()-2);
//Try block
try
{
//Convert the minute to integer
minuteFound = Integer.parseInt(minuteString);
}
//Catch the exception
catch (Exception e)
{
//Throw the exception
throw new InvalidFormattingException("Minute not an integer");
}
//Check the condition
if(minuteFound<0 || minuteFound>59)
//Throw the exception with a message
throw new InvalidMinuteException("Minute not in the range of 0 to 59");
//Check condition
if(!amString...
Want to see the full answer?
Check out a sample textbook solutionChapter 9 Solutions
Java: An Introduction to Problem Solving and Programming (7th Edition)
- in C# i need to Write the program BookExceptionDemo for the Peterman Publishing Company. Create a BookException class that is instantiated when a Book’s price exceeds 10 cents per page and whose constructor requires three arguments for title, price, and number of pages. Create an error message that is passed to the Exception class constructor for the Message property when a Book does not meet the price-to-pages ratio. For example, an error message: For Goodnight Moon, ratio is invalid. ...Price is $12.99 for 25 pages. Next, create a Book class that contains fields for title, author, price, and number of pages. Include properties for each field. Throw a BookException if a client program tries to construct a Book object for which the price is more than 10 cents per page. Finally, using the Book class, create an array of five Books. Prompt the user for values for each Book. To handle any exceptions that are thrown because of improper or invalid data entered by the user, set the Book’s…arrow_forwardThis is a java program question dont copy from any other source or internet for gods sake write the program and give me the output also write the code in your own imagination dont copy it from other source pleasearrow_forwardin C# i need to Write the program BookExceptionDemo for the Peterman Publishing Company. Create a BookException class that is instantiated when a Book’s price exceeds 10 cents per page and whose constructor requires three arguments for title, price, and number of pages. Create an error message that is passed to the Exception class constructor for the Message property when a Book does not meet the price-to-pages ratio. my errors are Test Case IncompleteComplete program walkthrough, test 1 InputBook1Author110.99200Book2Author219.99100Book3Author225.00600Book4Author35.0020Book5Author48.00120OutputBook1 by Author1 Price $10.99 200 pages.Book2 by Author2 Price $19.99 100 pages.Book3 by Author2 Price $25.00 600 pages.Book4 by Author3 Price $5.00 20 pages.Book5 by Author4 Price $8.00 120 pages. ResultsFor Book2, ratio is invalid....Price is $19.99 for 100 pages.For Book4, ratio is invalid....Price is $5.00 for 20 pages.Book1 by Author1 Price $10.99 200 pages.Book2 by Author2 Price $10.00 100…arrow_forward
- in c # i need to Write the program BookExceptionDemo for the Peterman Publishing Company. Create a BookException class that is instantiated when a Book’s price exceeds 10 cents per page and whose constructor requires three arguments for title, price, and number of pages. Create an error message that is passed to the Exception class constructor for the Message property when a Book does not meet the price-to-pages ratio. my errors are Test Case IncompleteComplete program walkthrough, test 1 InputBook1Author110.99200Book2Author219.99100Book3Author225.00600Book4Author35.0020Book5Author48.00120OutputEnter information for book #1:Title: Author: Price: Number of pages: Unhandled Exception:System.DivideByZeroException: Value was either too large or too small for a Decimal. at System.Decimal+DecCalc.VarDecDiv (System.Decimal& d1, System.Decimal& d2) [0x0003e] in <7b90a8780ac4414295b539b19eea7eea>:0 at System.Decimal.Divide (System.Decimal d1, System.Decimal d2) [0x00000] in…arrow_forwardJAVA EXCEPTION HANDLING:Define a new exception, called ExceptionLineTooLong, that prints out the error message "The strings is too long". Write a program that reads phrase and throws an exception of type ExceptionLineTooLong in the case where a string is longer than 80 characters. For example: Input Result The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.The quick brown fox jumped…arrow_forwardIn Java Attachedarrow_forward
- a) Write a method in java that searches a numeric array for a specified value. The method should return the subscript of the element containing the value if it is found in the array. If the value is not found , the method should throw an exceptionof the Exception class with the error message “Element not found”. b) Write an exception class that can be thrown when a negative number is passed to a method.arrow_forwardJava question Write a Thermostat class such that a user of the Thermostat class can create an objectof Thermostat and set it to the desired temperature within a pre-specified range. If theuser tries set the temperature outside this range it should throw a TemperatureTooHighor TemperatureTooLow exception. Use inheritance to create an exception superclassTemperatureOutofRange and subclasses TemperatureTooHigh andTemperatureTooLow.Sample Tester code:Thermostat t = new Thermostat(0, 100);t. setTemp(50); // Should be OK.t.setTemp(150); // Should throw TemperatureTooHigh exception.t.setTemp(-50); // Should throw TemperatureToolLow exception.Write a Tester class to demonstrate throwing and catching of exceptions. Show that thecatch specifying the superclass catches the subclass exceptions. The order of exceptionhandlers is important. If you try to catch a superclass exception type before a subclasstype, the compiler would generate errors. Also show the re-throwing of exceptions.arrow_forwardplease solve this important, thanks.arrow_forward
- Modify the MilTime class given under Final exam module. The class should implement the following exceptions: BadHour Throw when an invalid hour (< 0 or > 2359) is passed to the class. BadSeconds Throw when an invalid number of seconds (<0 or > 59) is passed to the class. Demonstrate the class in a driver program. Demo in the main function. the file: // MillTIme.cpp//#include "stdafx.h"#include <iostream>using namespace std;class Time{protected: int hour; int min; int sec;public: Time(int h, int m, int s) { hour = h; min = m; sec = s; } int getHour() { return hour; } int getMin() { return min; } int getSec() { return sec; }}; class MilTime : public Time{private: int milHours; int milSeconds;public: MilTime(int h = 0, int s = 0) : Time(0, 0, s) { if (h < 0 || h > 2359) { cout << "Hours must be in the range 0 - 2359.\n"; milHours = h;…arrow_forwardDevelop an exception class named InvalidMonthException that extends the Exception class. Instances of the class will be thrown based on the following conditions: The value for a month number is not between 1 and 12 The value for a month name is not January, February, March, … December Develop a class named Month. The class should define an integer field named monthNumber that holds the number of a month. For example, January would be 1, February would be 2, and so forth. In addition, provide the following methods: A no-argument constructor that sets the monthNumberto 1. An overloaded constructor that accepts the number of the month as an argument. The constructor should set the monthNumberfield to the parameter value if the parameter contains the value 1 – 12. Otherwise, throw an InvalidMonthException exception back to the caller. The exception should note that the month number was incorrect. An overloaded constructor that accepts a string containing the name of the month,…arrow_forwardA pedometer treats walking 2,000 steps as walking 1 mile. Write a stepsToMiles() method that takes the number of steps as an integer parameter and returns the miles walked as a double. The stepsToMiles() method throws an Exception object with the message "Exception: Negative step count entered." when the number of steps is negative. Complete the main() method that reads the number of steps from a user, calls the stepsToMiles() method, and outputs the returned value from the stepsToMiles() method. Use a try-catch block to catch any Exception object thrown by the stepsToMiles() method and output the exception message. Output each floating-point value with two digits after the decimal point, which can be achieved as follows:System.out.printf("%.2f", yourValue); Ex: If the input of the program is: 5345 the output of the program is: 2.67 Ex: If the input of the program is: -3850 the output of the program is: Exception: Negative step count entered. import java.util.Scanner; public class…arrow_forward
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningMicrosoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,