Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

public class Time { /* Three instance variables: 1) \'hour\': value of a hours a

ID: 3579719 • Letter: P

Question

public class Time {
/* Three instance variables:
1) 'hour': value of a hours as integer
2) 'min': value of a hours as integer
3) 'sec' : value of a seconds as integer */
/* A three-argument constructor to initialize all instance variables
with values given as parameters if they are valid values using 24 hours format */
/* A mutator method that sets the 'sec' field to a value given
as a parameter, but only if the given value is valid */
/* A toString method that returns time as 12 hours format */
/* An method that increments time by a positive number of seconds given as a parameter
only if value is less than or equal 59 */
}

Explanation / Answer

public class TimeClass
{
//Three instance variables:
//1) 'hour': value of a hours as integer
int hour;
//2) 'min': value of a hours as integer
int min;
//3) 'sec' : value of a seconds as integer
int sec;
//A three-argument constructor to initialize all instance variables
//with values given as parameters if they are valid values using 24 hours format
public TimeClass(int h, int m, int s)
{
if(h < 0 || h > 23)
hour = 0;
else
hour = h;
if(m < 0 || m > 59)
min = 0;
else
min = m;
if(s < 0 || s > 59)
sec = 0;
else
sec = s;   
}
//A mutator method that sets the 'sec' field to a value given
//as a parameter, but only if the given value is valid
public void setSec(int s)
{
if(s >= 0 && s < 60)
sec = s;
}
//A toString method that returns time as 12 hours format
public String toString()
{
String out = "";
if(hour > 12)
out = Integer.toString(hour % 12);
out += ":" + min + ":" + sec;
return out;
}
//An method that increments time by a positive number of seconds given as a parameter
//only if value is less than or equal 59
public void incrementTime(int s)
{
if(s < 60)
{
sec += s;
if(sec >= 60)
{
min++;
sec %= 60;
if(min >= 60)
{
hour++;
min %= 60;
if(hour >= 24)
hour %= 24;
}
}
}
}
}