Question

In: Computer Science

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"));
   }
}

* * * * Here are is the code I'm supposed to modify from our last assignment * * * *

*** HOURLY.java***

public class Hourly
{

    // Setting private Instance variables
    private String firstName;
    private String lastName;
    private double hoursWorked;
    private double payRate;
    private double weeklyPay;
    private static final int MAXREGULAR = 40;
  
    Scanner scan = new Scanner(System.in);
  
    // constructor
    public Hourly()
    {
        // set data field to zero
        this.firstName = "";
        this.lastName = "";
        this.hoursWorked = 0.0;
        this.payRate = 0.0;
    } // end of constructor
    
    // Set and get methods
    public String getFirstName()
    {
        return firstName;
    } // end of getter
  
    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    } // end of setter
  
    public String getLastName()
    {
        return lastName;
    } // end of getter
  
    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    } // end of setter
  
    public double getHoursWorked()
    {
        return hoursWorked;
    } // end of getter
  
    public void setHoursWorked(double hoursWorked)
    {
        while(hoursWorked < 1 || hoursWorked > 80)
        {
            System.out.println("\nYou must enter a number between 1 and 80. "
                        + "Please try again!\n");
          
            System.out.print("Enter the number of hours worked: ");
            hoursWorked = Double.parseDouble(scan.nextLine());
            }       
        this.hoursWorked = hoursWorked;
      
        } // end of setter
  
    public double getPayRate()
    {
        return payRate;
    } // end of getter
  
    public void setPayRate(double payRate)
    {
        while(payRate < 15 || payRate > 30)
        {
            System.out.println("\nYou must enter an hourly rate between "
                        + "$15 - $30. Please try again!\n");
            System.out.print("Enter hourly rate: $");
            payRate = Double.parseDouble(scan.nextLine());         
        }        
        this.payRate = payRate;
  
    } // end of setter
  
    // Method to return weeklyPay
    public double getPaycheck()
    {
        this.weeklyPay = this.hoursWorked * this.payRate;
      
        if (hoursWorked > MAXREGULAR) // if here was overtime. . .
        {
            double otHours = hoursWorked - MAXREGULAR; // calculate overtime hours
            double otPay = otHours * (payRate * 0.5); // pay "half" the rate for overtime hours worked
            weeklyPay = weeklyPay + otPay; // add overtime pay to regular pay
        }
      
        return weeklyPay;
  
    } // end of method getPaycheck

} //end of class Hourly

***HOURLYTEST.java***

public class HourlyTest
{

    public static void main(String[] args)
    {

        String firstName;
        String lastName;
        double hoursWorked;
        double payRate;

        Scanner scan = new Scanner(System.in);

        // Create Hourly class object
        Hourly hourly = new Hourly();

        // Ask user to enter values
        System.out.print("Enter first name: ");
        firstName = scan.nextLine();
        hourly.setFirstName(firstName);

        System.out.print("Enter last name: ");
        lastName = scan.nextLine();
        hourly.setLastName(lastName);

        System.out.print("Enter the number of hours worked: ");
        hoursWorked = Double.parseDouble(scan.nextLine());
        hourly.setHoursWorked(hoursWorked);

        System.out.print("Enter hourly rate: $");
        payRate = Double.parseDouble(scan.nextLine());
        hourly.setPayRate(payRate);

        // Call method to get weeklyPay
        double weeklyPay = hourly.getPaycheck();

        // if enter uses invalid data
        if (weeklyPay == 0.0)
        {          
            System.out.print("Enter the number of hours worked: ");
            hoursWorked = scan.nextInt();

            System.out.print("Enter hourly rate: $");
            payRate = scan.nextDouble();
            scan.nextLine();
      
            hourly.setHoursWorked(hoursWorked);
            hourly.setPayRate(payRate);
            weeklyPay = hourly.getPaycheck();
        }

        // Print weekly weeklyPay value
        System.out.println("\nThank you! \n" + firstName + " " + lastName +
                "'s weekly paycheck will be: $" + String.format("%.2f", weeklyPay));
        scan.close();

    } // end of main method

} // end of class HourlyTest

***Grading Rubric***

- Hourly Class validates hourly pay and hours worked correctly in a set method
- Hourly Class correctly throws an IllegalArgumentException if either is not valid
- Exception is caught (try/catch) and message is output to the user
- toString method is overridden in Hourly Class
- Main method prints object by its name only
- UML of the Hourly class

Solutions

Expert Solution

Hourly.java (modified)

public class Hourly

{

// Setting private Instance variables

private String firstName;

private String lastName;

private double hoursWorked;

private double payRate;

private double weeklyPay;

private static final int MAXREGULAR = 40;

Scanner scan = new Scanner(System.in);

// constructor

public Hourly()

{

// set data field to zero

this.firstName = "";

this.lastName = "";

this.hoursWorked = 0.0;

this.payRate = 0.0;

} // end of constructor

// Set and get methods

public String getFirstName()

{

return firstName;

} // end of getter

public void setFirstName(String firstName)

{

this.firstName = firstName;

} // end of setter

public String getLastName()

{

return lastName;

} // end of getter

public void setLastName(String lastName)

{

this.lastName = lastName;

} // end of setter

public double getHoursWorked()

{

return hoursWorked;

} // end of getter

public void setHoursWorked(double hoursWorked)

{

try{

if(hoursWorked < 1 || hoursWorked > 80)

{

System.out.println("\nYou must enter a number between 1 and 80. "

+ "Please try again!\n");

System.out.print("Enter the number of hours worked: ");

hoursWorked = Double.parseDouble(scan.nextLine());

}

else{

throw new IllegalArgumentException("Hourse worked must be positive and/or less than 80");

}

this.hoursWorked = hoursWorked;

}

catch(Exception e){

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

}

} // end of setter

public double getPayRate()

{

return payRate;

} // end of getter

public void setPayRate(double payRate)

{

try{

if(payRate < 15 || payRate > 30)

{

System.out.println("\nYou must enter an hourly rate between "

+ "$15 - $30. Please try again!\n");

System.out.print("Enter hourly rate: $");

payRate = Double.parseDouble(scan.nextLine());

}

else{

throw new IllegalArgumentException("Pay rate must be between 15 to 30 dollars a week");

}

this.payRate = payRate;

} // end of setter

catch(Exception e){

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

}

}

// Method to return weeklyPay

public double getPaycheck()

{

try{

this.weeklyPay = this.hoursWorked * this.payRate;

if (hoursWorked > MAXREGULAR) // if here was overtime. . .

{

double otHours = hoursWorked - MAXREGULAR; // calculate overtime hours

double otPay = otHours * (payRate * 0.5); // pay "half" the rate for overtime hours worked

weeklyPay = weeklyPay + otPay; // add overtime pay to regular pay

}

return weeklyPay;

}

catch(Exception e){

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

}

} // end of method getPaycheck

} //end of class Hourly

Time1.java

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() {

String str = String.format("Hour %d:%02d \n Minute: %02d \n Second: %s",

((hour == 0 || hour == 12) ? 12 : hour % 12),minute, second, (hour < 12 ? "AM" : "PM"));

return str;

}

}


Related Solutions

Lesson is on Inheritance and overriding the ToString ( ) method in Java: The program should...
Lesson is on Inheritance and overriding the ToString ( ) method in Java: The program should consist of 3 classes and will calculate an hourly paycheck.    - The superclass will contain fields for common user data for an employee (first name and last name) and a toString method that returns the formatted output of the names to the calling method.    - The subclass will calculate a paycheck for an hourly employee and will inherit from the superclass.   ...
I am in a class where I am supposed to be Minister of Foreign Affair representing...
I am in a class where I am supposed to be Minister of Foreign Affair representing India. I was invited to the G20 meeting to discuss and present negotiations with other countries of G20. The agenda will have two major items: international health cooperation and international economic cooperation. What negotiations could I do for India with other countries to improve the current situation and look for financial stability?
I am in a class where I am supposed to be a Civil Society Organization Representative...
I am in a class where I am supposed to be a Civil Society Organization Representative (CSO) representing India. I was invited to the G20 meeting to discuss and present negotiations with other countries of G20.The agenda will have two major items: international health cooperation and international economic cooperation. What negotiations could I do for India with other countries to improve the current situation and look for financial stability?
Scenario: I am creating a course for inclusion into an established nursing curriculum. I am supposed...
Scenario: I am creating a course for inclusion into an established nursing curriculum. I am supposed to describe the program level of the course am proposing. What do they mean by program level? This is a hypothetical community college with a two year nursing program.
I am supposed to read chapt. 7 and 8 about bond valuation and risk this week...
I am supposed to read chapt. 7 and 8 about bond valuation and risk this week . My assignment due wed is this . .. To prepare for this Discussion, consider your organization or one with which you are familiar, and its current riskiness. Develop an idea for a new product or service that has the potential to generate a good return on investment at reasonable or even high stand-alone risk but that has an opportunity to lower the organization's...
I thought for this type of question I am supposed to make a chart with the...
I thought for this type of question I am supposed to make a chart with the inventory, purchases, sales, etc., but instead, these questions are throwing me off for the little understanding I have on this new topic... Kayla Company uses the perpetual inventory system and the LIFO method. The following information is available for the month of June: June 1 Beginning inventory 200 units @ $5 12 Purchase on account 400 units @ $6 15 Sales on account 440...
I was wondering if I was doing a conversion right. I am supposed to take aqueous...
I was wondering if I was doing a conversion right. I am supposed to take aqueous HNO3 with a density of 1.42 g/mL and a mass percent of solution of 70% and convert that into molarity. Would the correct conversion be to take 70 g of HNO3 over 100 g of H2O multiplied by 1 mol HNO3 over 63.01 g HNO3 (the molar mass) and then multiply that by 1 g H2O over 0.001 L of H2O to get the...
C programming language. **I am aware that I am only supposed to ask one question so...
C programming language. **I am aware that I am only supposed to ask one question so if you cant do all of this could you please do part 2? thank you! This lab, along with your TA, will help you navigate through applying iterative statements in C. Once again we will take a modular approach to designing solutions to the problem below. As part of the lab you will need to decide which C selection structure and iterative structure is...
C programming language. **I am aware that I am only supposed to ask one question so...
C programming language. **I am aware that I am only supposed to ask one question so if you cant do all of this could you please do part 3? thank you! This lab, along with your TA, will help you navigate through applying iterative statements in C. Once again we will take a modular approach to designing solutions to the problem below. As part of the lab you will need to decide which C selection structure and iterative structure is...
Here, I detail the validation rules that you should implement and the error messages that must...
Here, I detail the validation rules that you should implement and the error messages that must be shown for invalid inputs: For login page: username input is required. If it is empty, show error message of “Please enter your username.” username input should be at least 5 character. If it is less that 5 character, show error message that “Please enter at least 5 characters.” password input is required. If it is empty, show error message of “Please enter your...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT