Question

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 that the number of hours worked that week is positive but not greater than 80. If either of these are invalid, your code should throw an illegal argument exception that is caught and an appropriate message is printed stating the error. If the rate of pay and the hours worked are valid, the instance variables should be set.
  • You will need to use a try/catch structure.
  • Override the object’s toString method in the Hourly class so that the main method prints the object’s information (name and weekly pay) by its name only (i.e. System.out.println(objectname);). Be sure to make the output look nice.

Here is the Case Study Code to Model After:

public class Time1 {
   private int hour; // 0 - 23
   private int minute; // 0 - 59
   private int second; // 0 - 59

   // set a new time value using universal time; throw an
   // exception if the hour, minute or second is invalid
   public void setTime(int hour, int minute, int second) {
      // validate hour, minute and second
      if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 ||
         second < 0 || second >= 60) {
         throw new IllegalArgumentException(             
            "hour, minute and/or second was out of range");
      }

      this.hour = hour;
      this.minute = minute;
      this.second = second;
   }

   // convert to String in universal-time format (HH:MM:SS)
   public String toUniversalString() {
      return String.format("%02d:%02d:%02d", hour, minute, second);
   }

   // convert to String in standard-time format (H:MM:SS AM or PM)
   public String toString() {
      return String.format("%d:%02d:%02d %s",       
         ((hour == 0 || hour == 12) ? 12 : hour % 12),
         minute, second, (hour < 12 ? "AM" : "PM"));
   }
}

Grading Rubric

Description

Points

Corrected code from last assignment

5

Hourly Class validates hourly pay and hours worked correctly in a set method

3

Hourly Class correctly throws an IllegalArgumentException if either is not valid

3

Exception is caught (try/catch) and message is output to the user

3

toString method is overridden in Hourly Class

3

Main method prints object by its name only

3

UML of the Hourly class

5

Total

25

0 0
Add a comment Improve this question Transcribed image text
Answer #1

public class Hourly {

      

       // instance variables

       private String name;

       private double pay_rate;

       private int hours_worked;

      

       // default constructor

       public Hourly()

       {

             name="";

             pay_rate=0;

             hours_worked=0;

       }

      

       // method to set the hourly rate of pay and number of hours worked

       public void set(double pay_rate, int hours_worked)

       {

             // try-catch block to validate the pay_rate and hours_worked

             try {

                    // check if hourly employee’s rate of pay is not less than $15.00/hour and not greater than $30.00

                    // check if number of hours worked that week is positive but not greater than 80

                    if(pay_rate < 15 || pay_rate > 30 || hours_worked <= 0 || hours_worked > 80) // invalid

                           throw new IllegalArgumentException("Hourly rate of pay or number of hours worked was out of range"); // throw an exception

                   

                    // valid data

                    this.pay_rate = pay_rate;

                    this.hours_worked = hours_worked;

             }catch(IllegalArgumentException e)

             {

                    System.out.println(e.getMessage());

             }

       }

      

       // method to set the name

       public void setName(String name)

       {

             this.name = name;

       }

      

       // prints the object's information (name and weekly pay)

       public String toString()

       {

             return("Name : "+name+" Weekly pay : $"+String.format("%.2f", pay_rate*hours_worked));

       }

       public static void main(String[] args) {

             Hourly hourly = new Hourly();

             // set the name

             hourly.setName("John Smith");

             hourly.set(35, 60); // throw an exception

            

             hourly.set(18, 60); // valid data

             System.out.println(hourly);

       }

}

//end of program

Output:

Add a comment
Know the answer?
Add Answer to:
Lesson is about Input validation, throwing exceptions, overriding toString Here is what I am supposed to...
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
  • JAVA. Create an application that uses a "PriorityQueue" to perform the following Uses the constructor that rece...

    JAVA. Create an application that uses a "PriorityQueue" to perform the following Uses the constructor that receives a "Comparator" object as an argument Stores 5 "Time1" objects using the "Time1" class shown in Fig. 8.1 on page 331. The class must be modified to implement the "Comparator" interface Displays the "Universal Time" in priority order Note: To determine the ordering when implementing the "Comparator" interface, convert the time into seconds (i.e., hours * 3600 + minutes * 60 + seconds),...

  • Instructions: Refer to the Timel class provided in Figure 8.1 in your Deitel book to complete...

    Instructions: Refer to the Timel class provided in Figure 8.1 in your Deitel book to complete the exercise. Make sure that you follow the Program Style and Readability guidelines found in the Start Here Folder. 1. Write a Point class. The Point class should be written as an abstract data type. 2. Include the following instance variables: a. an integer representing the x coordinate b. an integer representing the y coordinate c. The instance variables in your program should only...

  • By editing the code below to include composition, enums, toString; must do the following: Prompt the...

    By editing the code below to include composition, enums, toString; must do the following: Prompt the user to enter their birth date and hire date (see Fig. 8.7, 8.8 and 8.9 examples) in addition to the previous user input Create a new class that validates the dates that are input (can copy date class from the book) Incorporate composition into your class with these dates Use enums to identify the employee status as fulltime (40 or more hours worked for...

  • Please help with Java programming! This code is to implement a Clock class. Use my beginning...

    Please help with Java programming! This code is to implement a Clock class. Use my beginning code below to test your implementation. public class Clock { // Declare your fields here /** * The constructor builds a Clock object and sets time to 00:00 * and the alarm to 00:00, also. * */ public Clock() { setHr(0); setMin(0); setAlarmHr(0); setAlarmMin(0); } /** * setHr() will validate and set the value of the hr field * for the clock. * *...

  • Java Programming The program template represents a complete working Java program with one or more key...

    Java Programming The program template represents a complete working Java program with one or more key lines of code replaced with comments. Read the problem description and examine the output, then study the template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code. Compile and execute the program. Compare your output with the sample output provided. Modify class Time2 to include a tick method that increments the time stored in a Time2 object...

  • JAVA Use the class, Invoice, provided to create an array of Invoice objects. Class Invoice includes...

    JAVA Use the class, Invoice, provided to create an array of Invoice objects. Class Invoice includes four instance variables; partNumber (type String), partDescription (type String), quantity of the item being purchased (type int0, and pricePerItem (type double). Perform the following queries on the array of Invoice objects and display the results: Use streams to sort the Invoice objects by partDescription, then display the results. Use streams to sort the Invoice objects by pricePerItem, then display the results. Use streams to...

  • need help with this JAVA lab, the starting code for the lab is below. directions: The...

    need help with this JAVA lab, the starting code for the lab is below. directions: The Clock class has fields to store the hours, minutes and meridian (a.m. or p.m.) of the clock. This class also has a method that compares two Clock instances and returns the one that is set to earlier in the day. The blahblahblah class has a method to get the hours, minutes and meridian from the user. Then a main method in that class creates...

  • Add an HourlyPlusCommissionEmployee class to the PayrollSystem app by subclassing an existing class. A HourlyPlusCommissionEmployee is...

    Add an HourlyPlusCommissionEmployee class to the PayrollSystem app by subclassing an existing class. A HourlyPlusCommissionEmployee is a kind of CommissionEmployee with the following differences and specifications: HourlyPlusCommissionEmployee earns money based on 2 separate calculations: commissions are calculated by the CommissionEmployee base class hourly pay is calculated exactly the same as the HourlyEmployee class, but this is not inherited, it must be duplicated in the added class BasePlusCommissionEmployee inherits from CommissionEmployee and includes (duplicates) the details of SalariedEmployee. Use this as...

  • In this practical task, you need to implement a class called MyTime, which models a time...

    In this practical task, you need to implement a class called MyTime, which models a time instance. The class must contain three private instance variables: hour, with the domain of values between 0 to 23. minute, with the domain of values between 0 to 59. second, with the domain of values between 0 to 59. For the three variables you are required to perform input validation. The class must provide the following public methods to a user: MyTime() Constructor. Initializes...

  • I have a little problem about my code. when i'm working on "toString method" in "Course"...

    I have a little problem about my code. when i'm working on "toString method" in "Course" class, it always say there is a mistake, but i can not fix it: Student class: public class Student {    private String firstName;    private String lastName;    private String id;    private boolean tuitionPaid;       public Student(String firstName, String lastName, String id, boolean tuitionPaid)    {        this.firstName=firstName;        this.lastName=lastName;        this.id=id;        this.tuitionPaid=tuitionPaid;    }   ...

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