Question

Programming Assignment 1 Write a class called Clock. Your class should have 3 instance variables, one...

Programming Assignment 1

Write a class called Clock. Your class should have 3 instance variables, one for the hour, one for the minute and one for the second. Your class should have the following methods:

  • A default constructor that takes no parameters (make sure this constructor assigns values to the instance variables)
  • A constructor that takes 3 parameters, one for each instance variable
  • A mutator method called setHour which takes a single integer parameter. This method sets the value of the instance variable for the hour
  • A mutator method called setMinute which takes a single integer parameter. This method sets the value of the instance variable for the minute
  • A mutator method called setSecond which takes a single integer parameter. This method sets the value of the instance variable for the second
  • An accessor method called getHour which takes no parameters and returns the value of the instance variable for the hour
  • An accessor method called getMinute which takes no parameters and returns the value of the instance variable for the minute
  • An accessor method called getSecond which takes no parameters and returns the value of the instance variable for the second
  • A mutator method called tick. This will be similar to what we did in class, but this method will take an integer parameter. This parameter will specify how many ticks of the clock should take place. For example, tick(5) means to advance the clock 5 seconds. NOTE: The parameter can have a negative value, which means we tick backwards
  • An accessor method called toString which returns a string representation of the time, in the following format: HH:MM:SS AM or HH:MM:SS PM

I am including a main program for you to use to test your class, and also a screenshot of what the expected output should be. (Note this main program doesn’t explicitly test all of your methods, but they should still be provided.)

General notes that apply to all programming assignments:

  • Your class and all of its methods should be documented in accordance with the Javadoc Tool.  
  • Every method of every class should ensure the integrity of its instance variables. For example, an instance variable that holds the number of days in a month must always be 28, 29, 30 or 31.
  • You should always attempt to do your own work, but the truth is we often get outside help, intentionally or accidentally. If you get assistance from any person or resource, you must give credit to that person or resource. You won’t lose points. If you get outside help and don’t acknowledge it, you will receive a 0.
  • If you write your program with another classmate, only one of you should submit the assignment, including a note indicating who you worked with. You will both get full credit. Again, I encourage students to do their own work, but teamwork is not always a bad thing. No more than two may collaborate on a program.

Here is the main program, just copy and paste:

public class clockTest

{

    /**

     * A main program to test the Clock class

     */

    public static void main (String[] args)

    {

        Clock myClock = new Clock(23, 59, 59);

        System.out.println ("The time is " + myClock.toString());

        myClock.tick(1);

        System.out.println ("After adding one second, the time is " +

                myClock.toString());

        myClock.tick(-1);

        System.out.println ("After subtracting one second, the time is " +

                myClock.toString());

        myClock.tick(86400);

        System.out.println ("After adding a full day, the time is " +

                myClock.toString());

        myClock.tick(43200);

        System.out.println ("After adding a half day, the time is " +

                myClock.toString());

        myClock.tick(60);

        System.out.println ("After adding a minute, the time is " +

                myClock.toString());

        myClock.tick(-3600);

        System.out.println ("After subtracting an hour, the time is " +

                myClock.toString());

       

    }

}

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

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// Clock.java

public class Clock {

    // attributes

    private int hour;

    private int minute;

    private int second;

    // default constructor, initializes time to 12:00:00 AM or 0 hours 0 minutes

    // and 0 seconds

    public Clock() {

         hour = 0;

         minute = 0;

         second = 0;

    }

    // constructor taking values for each field

    public Clock(int hour, int minute, int second) {

         // validating and assigning values

         setHour(hour);

         setMinute(minute);

         setSecond(second);

    }

    // accessors and mutators for each field

    public int getHour() {

         return hour;

    }

    public void setHour(int hour) {

         // validating hour (in 24hr format) before assigning

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

             this.hour = hour;

    }

    public int getMinute() {

         return minute;

    }

    public void setMinute(int minute) {

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

             this.minute = minute;

    }

    public int getSecond() {

         return second;

    }

    public void setSecond(int second) {

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

             this.second = second;

    }

    // method to advance or withdraw given number of seconds from the current

    // time

    public void tick(int seconds) {

         // checking if seconds is positive

         if (seconds > 0) {

             // looping for seconds number of times

             for (int i = 0; i < seconds; i++) {

                 // advancing second

                 this.second++;

                 // if second go out of range, wrapping from 0 and advancing

                 // minute

                 if (this.second > 59) {

                      this.second = 0;

                      this.minute++;

                 }

                 // if minute is out of range, advancing hour

                 if (this.minute > 59) {

                      this.minute = 0;

                      this.hour++;

                 }

                 // if hour is out of range, wrapping around from 0

                 if (this.hour > 23) {

                      this.hour = 0;

                 }

             }

         } else {

             // looping for -seconds number of times

             for (int i = 0; i < -seconds; i++) {

                 // decrmenting second

                 this.second--;

                 // wrapping around second, minute or hour if necessary. this

                 // time, checking for the lower bounds

                 if (this.second < 0) {

                      this.second = 59;

                      this.minute--;

                 }

                 if (this.minute < 0) {

                      this.minute = 59;

                      this.hour--;

                 }

                 if (this.hour < 0) {

                      this.hour = 23;

                 }

             }

         }

    }

    public String toString() {

         // initially assuming time is "AM"

         String amPM = "AM";

         // if hour field is 12 or above, setting amPM to "PM"

         if (hour >= 12) {

             amPM = "PM";

         }

         // taking hour value

         int h = hour;

         // if hour is 0, setting h to 12 (0 hour in 24 hr format is 12 hour in

         // 12 hr format)

         if (h == 0) {

             h = 12;

         }

         // otherwise if h exceeds 12, subtracting 12 from time to convert 24 hr

         // time into 12 hr time

         else if (h > 12) {

             h = h - 12;

         }

         //returning a String in HH:MM:SS AM/PM format

         return String.format("%02d:%02d:%02d %s", h, minute, second, amPM);

    }

}

/*OUTPUT*/

The time is 11:59:59 PM

After adding one second, the time is 12:00:00 AM

After subtracting one second, the time is 11:59:59 PM

After adding a full day, the time is 11:59:59 PM

After adding a half day, the time is 11:59:59 AM

After adding a minute, the time is 12:00:59 PM

After subtracting an hour, the time is 11:00:59 AM

Add a comment
Know the answer?
Add Answer to:
Programming Assignment 1 Write a class called Clock. Your class should have 3 instance variables, one...
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
  • 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...

  • C++ Assignment: Create a class called FitnessMember that has only one variable, called name. The FitnessMember...

    C++ Assignment: Create a class called FitnessMember that has only one variable, called name. The FitnessMember class should have a constructor with no parameters, a constructor with a parameter, a mutator function and an accessor function. Also, include a function to display the name. Define a class called Athlete which is derived from FitnessMember. An Athlete record has the Athlete's name (defined in the FitnessMember class), ID number of type String and integer number of training days. Define a class...

  • In a project named 'DogApplication', create a class called 'Dog' 1. declare two instance variables in...

    In a project named 'DogApplication', create a class called 'Dog' 1. declare two instance variables in 'Dog' : name (String type) age (int type) 2. declare the constructor for the 'Dog' class that takes two input parameters and uses these input parameters to initialize the instance variables 3. create another class called 'Driver' and inside the main method, declare two variables of type 'Dog' and call them 'myDog' and 'yourDog', then assign two variables to two instance of 'Dog' with...

  • Create a class called DuplicateRemover. Create an instance method called remove that takes a single parameter...

    Create a class called DuplicateRemover. Create an instance method called remove that takes a single parameter called dataFile (representing the path to a text file) and uses a Set of Strings to eliminate duplicate words from dataFile. The unique words should be stored in an instance variable called uniqueWords. Create an instance method called write that takes a single parameter called outputFile (representing the path to a text file) and writes the words contained in uniqueWords to the file pointed...

  • You will write a class called Shoe.java Shoe.java should have Three instance variables String brand (cannot...

    You will write a class called Shoe.java Shoe.java should have Three instance variables String brand (cannot be blank) double size (from 5 to 12) int color (a number from 1 to 5 representing one of 5 colors) This code is to control the amount of colors. the colors represented are as follows 1. red 2. green 3. blue 4. black 5. grey One constructor, one get method per instance variable, one set method per instance variable. You will need a...

  • *Python* INTRODUCTION: The goal of this programming assignment is to enable the student to practice object-oriented...

    *Python* INTRODUCTION: The goal of this programming assignment is to enable the student to practice object-oriented programming using classes to create objects. PROBLEM DEFINITION: Write a class named Employee that holds the following data about an employee in attributes: name, IDnumber, department, jobTitle The class should have 8 methods as follows:  For each attribute, there should be a method that takes a parameter to be assigned to the attribute. This is known as a mutator method.  For each...

  • Write a program that meets the following requirements: Sandwich Class Create a class called Sandwich which has the following instance variables. No other instance variables should be used: - ingredi...

    Write a program that meets the following requirements: Sandwich Class Create a class called Sandwich which has the following instance variables. No other instance variables should be used: - ingredients (an array of up to 10 ingredients, such as ham, capicola, American cheese, lettuce, tomato) -condiments (an array of up to 5 condiments, such as mayonnaise, oil, vinegar and mustard) Create a two argument constructor Write the getters and setters for the instance variables Override the toString method using the...

  • Java Project Requirements: Account class Superclass Instance variables clearPassword String Must be at least 8 characters...

    Java Project Requirements: Account class Superclass Instance variables clearPassword String Must be at least 8 characters long encryptedPassword : String key int Must be between 1 and 10(inclusive) accountId - A unique integer that identifies each account nextIDNum – a static int that starts at 1000 and is used to generate the accountID no other instance variables needed. Default constructor – set all instance variables to a default value. Parameterized constructor Takes in clearPassword, key. Calls encrypt method to create...

  • Answer the following: 1.        Create a Class Car with the following instance variables: model (String), Brand...

    Answer the following: 1.        Create a Class Car with the following instance variables: model (String), Brand (String), maxspeed (double) Note: use encapsulation (all variables are private). (3 Marks) 2.        Create a non-default constructor for Class Car which takes 3 parameters. (2 Marks) 3.        Create a get and set methods for instance variable model variable only. (2 Marks) 4.        Create PrintInfo() method which prints all three instance variables. (2 Marks) 5.        Create a subclass GasCar with instance variable TankSize (double).. (2...

  • The purpose of this assignment is to write a class Checker that can be used as...

    The purpose of this assignment is to write a class Checker that can be used as a part of a checker game program. Open an New Project in Qt Creator, and name it ChGame. Right click on the name of the class, and add a new C++ class named Checker. This will create the new les Checker.h and Checker.cpp. You will need to modify both Checker.h and Checker.cpp for this assignment. (The main function I used for testing my functions...

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