Reputation: 1657
Add two more constructors that are analogous to the set Time methods described in parts c and d.
Part c: Write a method setTime(hour, minute) that sets time if the given values are valid.
public void SetTime(int newHour, int newMinute)
{
if (hourIsValid = true)
hour = newHour;
if (minuteIsValid = true)
minute = newMinute;
}
Part d: Write another method setTime(hour,minute,isAm) that sets the time if the given values are valid. The given hour should be in the range of 1 to 12. The parameter isAM is true if the time is an a.m time and false otherwise.
public void SetTime(int newHour, int newMinute, boolean isAM)
{
if (hour >=0 && hour < 12)
{ isAM = true;
hour = newHour;}
if (minuteIsValid = true)
minute = newMinute;
if (isAM = true)
System.out.println ( hour + "a.m");
else
nightHour = hour % 12;
System.out.println( nightHour + "p.m");
}
That is what i produced so far, what is being asked to be produced by analogous? I know it means similar but w does it mean like for part C just the two separate like SetHour and SetMinute?
Upvotes: 0
Views: 522
Reputation: 54695
The question simply means write two constructors for the class in question (you haven't mentioned the name of it) that perform the same function as the methods described in part (c) and (d); i.e. they initialise the class with the hour and minute, and with the hour, minute and "am" flag respectively.
For example:
public void setTime(int hour, int minute)
public Time(int hour, int minute)
Note that the constructor can simply chain to the method call; e.g.
public Time(int hour, int minute) {
setTime(hour, minute);
}
However, typically a constructor may be used to initialise final fields and hence will not chain to a setter; e.g.
public Time(int hour, int minute) {
this.hour = hour;
this.minute = minute;
}
Upvotes: 1
Reputation: 4024
Every class can have multiple constructors, each one can get different variables.
For this homework, you should add constructors that get the values similar to the setters functions, and use the setters:
public ClassName(int newHour, int newMinute)
{
SeTime(newHour, newMinute);
}
Upvotes: 2