(Homework Solution): Java Question: Write a Java class called MyTime that represents a 24 hour clock (i.e

Java Question:

Write a Java class called MyTime that represents a 24 hour clock (i.e. ranges from 00:00:00 to 23:59:59). It should have private integer instance variables for hour, minute, and second, and should have the following public methods:

public void setTime(int hour, int minute, int second) – this method will set the object’s instance variables to the specified 24 hour time.. It must first test its parameter values for a valid time being supplied by the calling code, according to the following rules:,

Hour must be in the range of 0 to 23.

Minute and second must be in the range of 0 to 59.

If any of the parameters are outside these limits, it must set all three instance variables to zero (representing midnight). If the parameters represent a valid time, then it sets the instance variables to that time.

public int getHour() – this method returns the object’s hour value.

public int getMinute() – this method returns the object’s minute value.

public int getSecond() – this method returns the object’s second value.

public boolean equals(MyTime other) – this method compares the time represented by two MyTime objects. It compares the time represented by this MyTime object with the time represented by the parameter other MyTime object, returning true if they represent the same time. The parameter other is a reference to another MyTime object passed into this method by the calling code. To check for equality, this method must compare the three instance variables of this MyTime object with the three instance variables of the other MyTime object, returning true if all three match, and false otherwise. This method is required to compare the value of two MyTime objects, as the == operator compares the two operand’s object references (memory addresses) to see if they refer to the same object (which is not what we want).

public String toString() – this method returns the object’s time value formatted as a String of the formhh:mm:ss AM or PM. The minutes and seconds must be two digits (ie. if less than 10, add a leading zero), but the hour doesn’t have a leading zero. Call the twoDigits method to convert the minutes and seconds values to strings. The displayed hour is in the range 1 to 12. Midnight is returned as 12:00:00 AM,  noon as 12:00:00 PM, 9 AM as 9:00:00 AM, 3 PM as 3:00:00 PM. (Note – there is no 0 AM or 0 PM in this format, it must be 12 AM (midnight) or 12 PM (noon)). This method should not change the instance variables. Use a local variable to hold the hour value that must range from 1 to 12.

public String toUniversalString() – this method returns the object’s time value formatted as a String of the form hh:mm:ss in 24 hour format (military time). The hours, minutes, and seconds must all be two digits. Call the twoDigits method to convert each value to a string. Midnight is returned as 00:00:00noon as 12:00:00, 9 AM as 09:00:00, 3 PM as 15:00:00. This method should not change the instance variables.

private String twoDigits(int val) – this private method returns it’s int parameter value formatted as a two digit String (e.g calling it with the value 5 returns the string “05”, calling it with the value 20 returns the string “20”). It can use either the String.valueOf(int) method or Integer.toString(int) method to do the conversion. Call twoDigits() from the toString and  toUniversalString methods in order to format the individual time fields as two digits where required. This method is made private so it cannot be called by methods in other classes.

Note: the main() method for testing this class is supplied for you in the MyTimeDemo.java file seen at the bottom. Do NOT write your own main() method. the main method codes is provided at the end in the MyTimeDemo.java.

Sample Output should be like below:

Enter hour, minute, and second (-1 to exit)
10 20 30

Values read were: 10 20 30
10:20:30 AM
10:20:30
hour is 10 minute is 20 second is 30

Enter hour, minute, and second (-1 to exit)
13 5 5

Values read were: 13 5 5
1:05:05 PM
13:05:05
hour is 13 minute is 5 second is 5

Enter hour, minute, and second (-1 to exit)
25 10 20

Values read were: 25 10 20
12:00:00 AM
00:00:00
hour is 0 minute is 0 second is 0

Enter hour, minute, and second (-1 to exit)
-1

Test Data

Use all the following test data, followed by some of your own examples.

10 20 30
1 1 1
13 1 1
0 0 0
23 59 59
12 0 0
6 30 0
24 30 15
12 60 15
12 30 60

Use the MyTime.java source codes below as a starting template for writing your MyTime class.  It contains an outline of the class and methods needed, and you’ll add the implementation code for each of the methods. Make sure to provide approriate comments for your codes in the MyTime.java file

/**
 * MyTime - a simple time class
 *
 * Add code to replace the temporary 'return' statements in the methods,
 * and additional parameter checking code in the setTime method, etc.
 * The temporary 'return' statements are needed to compile OK until
 * you replace them with the actual code.
 */
public class MyTime
{
    // Instance variables holding the time (in 24 hour universal form).
    private int mHour;      // 0 - 23
    private int mMinute;    // 0 - 59
    private int mSecond;    // 0 - 59

    /**
     * Sets the time value for this MyTime object. If *any* of the parameter
     * values are out of range, the time is set to 00:00:00.
     *
     * @param hour      the hour (0 to 23).
     * @param minute    the minute (0 to 59).
     * @param second    the second (0 to 59).
     */
    public void setTime(int hour, int minute, int second)
    {

        // TODO - add parameter checking code, and set the instance variables.
        // If any of the parameters are out of range, set all the instance variables to zero.
    }

    /**
     * Returns the hour value represented by this MyTime.
     *
     * @return the hour value of this object as an int.
     */
    public int getHour()
    {
        return 0;  // TODO - replace
    }

    /**
     * Returns the minute value represented by this MyTime.
     *
     * @return the minute value of this object as an int.
     */
    public int getMinute()
    {
        return 0;  // TODO - replace
    }

    /**
     * Returns the second value represented by this MyTime.
     *
     * @return  the second value of this object as an int.
     */
    public int getSecond()
    {
        return 0;  // TODO - replace
    }

    /**
     * Compares this MyTime object against another MyTime object.
     * The result is true if and only if the argument is not null
     * and represents a time that is the same time as represented
     * by this object
     *
     * @param  other    the object to be compared.
     * @returns  true if both objects represent the same time value,
     *           false otherwise.
     */
    public boolean equals(MyTime other)
    {
        // TODO - add code to return 'true' if 'this' MyTime matches
        // the time values in the 'other' MyTime object, else return false.

        return false;
    }

    /**
     * Returns the time of this MyTime object in HH:MM:SS AM/PM form.
     * Ex: time values of 9,15,0 returns:  9:15:00 AM
     * Ex: time values of 23,30,0 returns:  11:30:00 PM
     *
     * @return the time value represented by this object as a String
     *         formatted as HH:MM:SS AM/PM .
     */
    public String toString()
    {
        String result = "";

        // TODO - add code to format the time in the instance variables
        // into HH:MM:SS AM/PM time (hour ranges from 1 to 12, AM or PM)
        // as a string and return it. Call the twoDigits() method to
        // convert each int value to String.

        return result;
    }

    /**
     * Returns the time of this MyTime object in 24 hour universal form.
     *
     * @return the time value represented by this object as a String
     *         formatted as HH:MM:SS universal time.
     */
    public String toUniversalString()
    {
        String result = "";

        // TODO - add code to format the time in the instance variables
        // into HH:MM:SS universal time (hour ranges from 0 to 23)
        // as a string and return it. Call the twoDigits() method to
        // convert each int value to String.

        return result;
    }

    /**
     * Returns the parameter value as a two digit String (with leading 0 if needed)
     *
     * @return the parameter 'value' formatted as a two digit String
     *         (with leading zero if needed).
     */
    private String twoDigits(int value)
    {
        String result = "";

        // TODO - Use the Integer.toString(int) method to convert
        // 'value' to String format, and add a leading "0" if
        // value is less than 10 in order to return a string with
        // two digits.

        return result;
    }

}

Use the below MyTimeDemo.java vodes to test your completed MyTime.java class. It contains just the supplied main() method test code for testing your MyTime class:

/**
 * MyTimeDemo - tests the MyTime class
 *
 * The MyTime class must be compiled before this class can be compiled.
 */
import java.util.Scanner;
public class MyTimeDemo
{
    /**
     * main
     */
    public static void main (String[] args)
    {
        Scanner sc = new Scanner(System.in);

        // Create a MyTime object and set to noon (12 PM).
        MyTime noon = new MyTime();
        noon.setTime(12, 0, 0);

        MyTime wakeup = new MyTime();
        wakeup.setTime(6, 30, 0);

        // Ask for time to be input, then create a new MyTime and set the time
        int inHour, inMinute, inSecond;
        do {
            System.out.println();
            System.out.println("Enter hour minute and second (-1 to exit)");
            inHour = sc.nextInt();
            if (-1 == inHour)
                break;
            inMinute = sc.nextInt();
            inSecond = sc.nextInt();
            System.out.println();
            System.out.println("Values read were: " + inHour + " " +
                               inMinute + " " + inSecond);

            // Create a new MyTime object
            MyTime t = new MyTime();

            // Set the time to the time read from the keyboard
            t.setTime(inHour,inMinute,inSecond);

            System.out.println(t.toString());
            System.out.println(t.toUniversalString());
            System.out.println("hour is " + t.getHour() + "  minute is " +
                                t.getMinute() + "  second is " + t.getSecond());

            // Test if the time read matches the 'noon' MyTime object's value.
            if (t.equals(noon))
                System.out.println("Matches noon time");
            // Test if the time read matches the 'wakeup' MyTime objet's value
            if (t.equals(wakeup))
                System.out.println("It's time to wakeup!");

        } while (-1 != inHour);

        // Keep console window alive until 'enter' pressed (if needed).
        System.out.println();
        System.out.println("Done - press enter key to end program");
        String junk = sc.nextLine();
    }
}

Expert Answer

answers

/**

* MyTime – a simple time class

*

* Add code to replace the temporary ‘return’ statements in the methods, and

* additional parameter checking code in the setTime method, etc. The temporary

* ‘return’ statements are needed to compile OK until you replace them with the

* actual code.

*/

class MyTime {

// Instance variables holding the time (in 24 hour universal form).

private int mHour; // 0 – 23

private int mMinute; // 0 – 59

private int mSecond; // 0 – 59

/**

* Sets the time value for this MyTime object. If *any* of the parameter values

* are out of range, the time is set to 00:00:00.

*

* @param hour

* the hour (0 to 23).

* @param minute

* the minute (0 to 59).

* @param second

* the second (0 to 59).

*/

public void setTime(int hour, int minute, int second) {

// TODO – add parameter checking code, and set the instance variables.

// If any of the parameters are out of range, set all the instance variables to

// zero.

if (hour >= 0 && hour <= 23)

this.mHour = hour;

else {

this.mHour = 0;

this.mMinute = 0;

this.mSecond = 0;

return;

}

if (minute >= 0 && minute <= 59)

this.mMinute = minute;

else {

this.mHour = 0;

this.mMinute = 0;

this.mSecond = 0;

return;

}

if (second >= 0 && second <= 59)

this.mSecond = second;

else {

this.mHour = 0;

this.mMinute = 0;

this.mSecond = 0;

}

}

/**

* Returns the hour value represented by this MyTime.

*

* @return the hour value of this object as an int.

*/

public int getHour() {

return mHour; // TODO – replace

}

/**

* Returns the minute value represented by this MyTime.

*

* @return the minute value of this object as an int.

*/

public int getMinute() {

return mMinute; // TODO – replace

}

/**

* Returns the second value represented by this MyTime.

*

* @return the second value of this object as an int.

*/

public int getSecond() {

return mSecond; // TODO – replace

}

/**

* Compares this MyTime object against another MyTime object. The result is true

* if and only if the argument is not null and represents a time that is the

* same time as represented by this object

*

* @param other

* the object to be compared.

* @returns true if both objects represent the same time value, false otherwise.

*/

public boolean equals(MyTime other) {

// TODO – add code to return ‘true’ if ‘this’ MyTime matches

// the time values in the ‘other’ MyTime object, else return false.

if (this == other)

return true;

if (other == null)

return false;

if (getClass() != other.getClass())

return false;

MyTime old = (MyTime) other;

if (mHour != old.mHour)

return false;

if (mMinute != old.mMinute)

return false;

if (mSecond != old.mSecond)

return false;

return true;

}

/**

* Returns the time of this MyTime object in HH:MM:SS AM/PM form. Ex: time

* values of 9,15,0 returns: 9:15:00 AM Ex: time values of 23,30,0 returns:

* 11:30:00 PM

*

* @return the time value represented by this object as a String formatted as

* HH:MM:SS AM/PM .

*/

public String toString() {

String result = “”, zone = “”;

int time = 0;

// TODO – add code to format the time in the instance variables

// into HH:MM:SS AM/PM time (hour ranges from 1 to 12, AM or PM)

// as a string and return it. Call the twoDigits() method to

// convert each int value to String.

if (mHour >= 12)

zone = “PM”;

else

zone = “AM”;

if (mHour > 12)

time = mHour – 12;

else

time = mHour;

 

if (mHour == 0)

time = 12;

 

 

result = twoDigits(time) + “:” + twoDigits(mMinute) + “:” + twoDigits(mSecond) + ” “;

result += zone;

return result;

}

/**

* Returns the time of this MyTime object in 24 hour universal form.

*

* @return the time value represented by this object as a String formatted as

* HH:MM:SS universal time.

*/

public String toUniversalString() {

String result = “”;

// TODO – add code to format the time in the instance variables

// into HH:MM:SS universal time (hour ranges from 0 to 23)

// as a string and return it. Call the twoDigits() method to

// convert each int value to String.

result += twoDigits(mHour) + “:” + twoDigits(mMinute) + “:” + twoDigits(mSecond);

return result;

}

/**

* Returns the parameter value as a two digit String (with leading 0 if needed)

*

* @return the parameter ‘value’ formatted as a two digit String (with leading

* zero if needed).

*/

private String twoDigits(int value) {

String result = “”;

// TODO – Use the Integer.toString(int) method to convert

// ‘value’ to String format, and add a leading “0” if

// value is less than 10 in order to return a string with

// two digits.

if (value < 10)

result = “0” + Integer.toString(value);

else

result = Integer.toString(value);

return result;

}

}

—————————————————————————————————————-

See Output

M.j E AllCode 自AllCode 目output.txt 를 input.txt Eoutput.ytxt MM FileRead Write yl imeDemo.java × »99 129 130 131 132 133 134 135 //into HH:MM:SS AM/PM time Chour ranges from 1 to 12, AM or PM) // as a string and return it. Call the twoDigitsO method to // convert each int value to String. if (mHour >- 12) zone PM else zoneAM Console X «terminated > MyTimeDemo [Java Application] /Library/Java/JavaVirtualMachines/jak 1.8.0_18 1.jdk/Contents/Home/bin/java (30-Sep-2018, 2:59:44 PI Enter hour minute and second (-1 to exit) 13 5 5 Values read were: 13 5 5 01:05:05 PM 13:05:05 hour is 13 minute is 5 second is 5 Enter hour minute and second (-1 to exit) 25 10 20 Values read were: 25 10 20 12:00:00 AM 00:00:00 hour is 0 minute is 0 second is 0 Enter hour minute and second (-1 to exit) 10 20 30 Values read were: 10 20 30 10:20:30 AM 10:20:30 hour is 10 minute is 20 second is 30 Enter hour minute and second (-1 to exit) Done press enter key to end program

iWriteHomework
Order NOW for a 10% Discount
Pages (550 words)
Approximate price: -

Why Us?

Top Quality and Well-Researched Papers

All ourbpapers are written from scratch. In fact, Clients who ask for paraphrasing services are highly discouraged. We have writers ready to craft any paper from scratch and deliver quality ahead of time.

Professional and Experienced Academic Writers

Our writers keeps you posted on your papers progress - providing you with paper outline/draft. You are also at liberty to communicate directly with your writer.

Free Unlimited Revisions

If you think we missed something, send your order for a free revision. You have 10 days to submit the order for review after you have received the final document. You can do this yourself after logging into your personal account or by contacting our support.

Prompt Delivery and 100% Money-Back-Guarantee

All papers are always delivered on time, in many cases quite ahead of time. In case we need more time to master your paper, we may contact you regarding the deadline extension. In case you cannot provide us with more time, a 100% refund is guaranteed.

Original & Confidential

We use several writing tools checks to ensure that all documents you receive are free from plagiarism. Our editors carefully review all quotations in the text. We also promise maximum confidentiality in all of our services.

24/7 Customer Support

Our support agents are available 24 hours a day 7 days a week and committed to providing you with the best customer experience. Get in touch whenever you need any assistance.

Try it now!

Calculate the price of your order

Total price:
$0.00

How it works?

Follow these simple steps to get your paper done

Place your order

Fill in the order form and provide all details of your assignment.

Proceed with the payment

Choose the payment system that suits you most.

Receive the final file

Once your paper is ready, we will email it to you.

Our Services

No need to work on your paper at night. Sleep tight, we will cover your back. We offer all kinds of writing services.

Essays

Essay Writing Service

No matter what kind of academic paper you need and how urgent you need it, you are welcome to choose your academic level and the type of your paper at an affordable price. We take care of all your paper needs and give a 24/7 customer care support system.

Admissions

Admission Essays & Business Writing Help

An admission essay is an essay or other written statement by a candidate, often a potential student enrolling in a college, university, or graduate school. You can be rest assurred that through our service we will write the best admission essay for you.

Reviews

Editing Support

Our academic writers and editors make the necessary changes to your paper so that it is polished. We also format your document by correctly quoting the sources and creating reference lists in the formats APA, Harvard, MLA, Chicago / Turabian.

Reviews

Revision Support

If you think your paper could be improved, you can request a review. In this case, your paper will be checked by the writer or assigned to an editor. You can use this option as many times as you see fit. This is free because we want you to be completely satisfied with the service offered.

× Contact Live Agents