152k views
1 vote
Create a class called Clock to represent a Clock. It should have three private instance variables: An int for the hours, an int for the minutes, and an int for the seconds. The class should include a threeargument constructor and get and set methods for each instance variable. Override the method toString which should return the Clock information in the same format as the input file (See below). Read the information about a Clock from a file that will be given to you on Blackboard, parse out the three pieces of information for the Clock using a StringTokenizer, instantiate the Clock and store the Clock object in two different arrays (one of these arrays will be sorted in a later step). Once the file has been read and the arrays have been filled, sort one of the arrays by hours using Selection Sort. Display the contents of the arrays in a GUI that has a GridLayout with one row and two columns. The left column should display the Clocks in the order read from the file, and the right column should display the Clocks in sorted order.

User Kwang
by
4.9k points

1 Answer

6 votes

Answer:

public class Clock

{

private int hr; //store hours

private int min; //store minutes

private int sec; //store seconds

public Clock ()

{

setTime (0, 0, 0);

}

public Clock (int hours, int minutes, int seconds)

{

setTime (hours, minutes, seconds);

}

public void setTime (int hours, int minutes, int seconds)

{

if (0 <= hours && hours < 24)

hr = hours;

else

hr = 0;

if (0 <= minutes && minutes < 60)

min = minutes;

else

min = 0;

if (0 <= seconds && seconds < 60)

sec = seconds;

else

sec = 0;

}

//Method to return the hours

public int getHours ( )

{

return hr;

}

//Method to return the minutes

public int getMinutes ( )

{

return min;

}

//Method to return the seconds

public int getSeconds ( )

{

return sec;

}

public void printTime ( )

{

if (hr < 10)

System.out.print ("0");

System.out.print (hr + ":");

if (min < 10)

System.out.print ("0");

System.out.print (min + ":");

if (sec < 10)

System.out.print ("0");

System.out.print (sec);

}

//The time is incremented by one second

//If the before-increment time is 23:59:59, the time

//is reset to 00:00:00

public void incrementSeconds ( )

{

sec++;

if (sec > 59)

{

sec = 0;

incrementMinutes ( ); //increment minutes

}

}

///The time is incremented by one minute

//If the before-increment time is 23:59:53, the time

//is reset to 00:00:53

public void incrementMinutes ( )

{

min++;

if (min > 59)

{

min = 0;

incrementHours ( ); //increment hours

}

}

public void incrementHours ( )

{

hr++;

if (hr > 23)

hr = 0;

}

public boolean equals (Clock otherClock)

{

return (hr == otherClock.hr

&& min == otherClock.min

&& sec == otherClock.sec);

}

}

User Daran
by
4.5k points