I'm working on the mooc.fi assignments and I'm really stuck at the clock assignment. I don't want a solution, but advice on how to reach my solution as I'm still learning and really need to figure out how to work through this. If you're unfamiliar with mooc, the current section is on how to work with objects within objects.
It consists of three classes, the main creates the clock and the boundedcounter is what makes the clock tick. I get it to print onto the screen, but when a custom starting input is entered it prints that first, then resets the value back to zero. Can someone point me in the right direction please? Sorry for the basic question, still trying to learn this java language!
Main
public class Main {
public static void main(String[] args) {
Clock clock = new Clock(23, 59, 50);
int i = 0;
while( i < 20) {
System.out.println( clock );
clock.tick();
i++;
}
}
}
Clock
public class Clock {
private BoundedCounter hours;
private BoundedCounter minutes;
private BoundedCounter seconds;
public Clock(int hoursAtBeginning, int minutesAtBeginning, int secondsAtBeginning) {
// the counters that represent hours, minutes and seconds are created and set to have the correct initial values
this.hours = new BoundedCounter(hoursAtBeginning);
this.hours.setValue(hoursAtBeginning);
this.minutes = new BoundedCounter(minutesAtBeginning);
this.minutes.setValue(minutesAtBeginning);
this.seconds = new BoundedCounter(secondsAtBeginning);
this.seconds.setValue(secondsAtBeginning);
}
public void tick() { //increases the time
this.seconds.next();
if (this.seconds.getValue() == 0) {
this.minutes.next();
if (this.minutes.getValue() == 0) {
this.hours.next();
}
}
}
public String toString() {
// returns the string representation
return hours + ":" + minutes + ":" + seconds;
}
}
BoundedCounter
public class BoundedCounter {
private int value;
private int upperLimit;
public BoundedCounter(int upperLimit) {
// write code here
this.value = 0;
this.upperLimit = upperLimit;
}
public void next() {
// write code here
if (value < upperLimit) {
value++;
} else {
value = 0;
}
}
public int getValue() {
return value;
}
public void setValue(int value) {
if (value >= 0 && value <= upperLimit) {
this.value = value;
}
}
#Override
public String toString() {
if (value < 10) {
return "0" + value;
}
return "" + value;
}
}
You're passing the current time to BoundedCounter.
this.hours = new BoundedCounter(hoursAtBeginning);
this.minutes = new BoundedCounter(minutesAtBeginning);
this.seconds = new BoundedCounter(secondsAtBeginning);
But BoundedCounter is expecting the upper bound, not the current time.
public BoundedCounter(int upperLimit) {
Since whatever time you pass it is considered the upper limit, the next tick rolls over to 0:0:0.
BoundedCounter.next() sets value to 0 if value is not less than upperLimit. Since the Clock constructor always initializes all BoundedCounter value values to be equal to upperLimit, the first call to Clock.tick() will cause all BoundedCounter objects to set their value values to 0.
Besides the corrections:
this.hours = new BounedCounter(int upperLimit);
this.minutes = new BounedCounter(int upperLimit);
this.seconds = new BounedCounter(int upperLimit);
the method public void tick() has to be composed as shown below, otherwise when the value of the minutes is 00 while the value of the seconds is 01, 02, ...59, the value of the hours will be increased with every second, and the result will be 01:00:01, 2:00:02, 3:00:03, etc.
public void tick() {
this.seconds.next();
if (this.seconds.getValue() == 0) {
this.minutes.next();
}
if (this.minutes.getValue() == 0 && this.seconds.getValue() == 0) {
this.hours.next();
}
}
Related
I am trying to create a digital clock an am currently trying to fix my incrementMinutesBy method.
I need this method to increase both the minutes and if necessary the hours. I need the final this.minutes to be the sum of the previous this.minutes and the parameter, modulo the number of minutes in an hour.
I also need the final this.hours to be the sum of the previous this.minutes and the parameter, divided by the number of minutes in an hour. My method so far begins on line 94.
public class DigitalClock
{
private int currentHour;
private int currentMinutes;
public int getHour()
{
return currentHour;
}
public void setHour(int currentHour)
{
this.currentHour = currentHour;
}
public int getMinutes()
{
return currentMinutes;
}
public void setMinutes(int currentMinutes)
{
this.currentMinutes = currentMinutes;
}
public static final int HOUR_MAX = 23; // Refactored hourly max
public static final int HOUR_MIN = 0; // Refactored hourly min
public static final int MINUTES_MAX = 59; // Refactored minute max
public static final int MINUTES_MIN = 0; // Refactored minute min
public static final int TOTAL_NUMBERS_HOURS = 24;
public static final int TOTAL_NUMBERS_MINUTES = 60;
/**
* Creates a new digital clock with the time set at the given
* hours and minutes.
*
* #precondition 0 <= hour <= 23 AND 0 <= minutes <= 59
* #postcondition getHour()==hour AND getMinutes()==minutes
*
* #param hour the hour to set for the time
* #param minutes the minutes to set for the time
*/
public DigitalClock (int hour, int minutes) // 2-parameter constructor (parameters: int hour and int minutes)
{
// enforcing hourly preconditions using appropriate ranges
if (hour >= HOUR_MIN && hour <= HOUR_MAX){
currentHour = hour;
}
else {
currentHour = 0;
//throw an exception on invalid hour's input
throw new IllegalArgumentException("Invalid input for Hours");
}
// enforcing minute preconditions using appropriate ranges
if (minutes >= MINUTES_MIN && minutes <= MINUTES_MAX) {
currentMinutes = minutes;
}
else {
currentMinutes = 0;
//throw an exception on invalid minute's input
throw new IllegalArgumentException("Invalid input for Minutes");
}
}
/**
* Advances the entire clock by the given number of hours.
* If the hours advances past 23 they wrap around.
*
* #precondition hours >= 0
* #postcondition the clock has moved forward
* by the appropriate number of hours
*
* #param hours the number of hours to add
*/
public void incrementHoursBy(int hour)
{
int h = getHour()+hour; {
// if statement enforcing precondition
if(h>HOUR_MAX)
h%=TOTAL_NUMBERS_HOURS;
// increasing this.hours by the parameter
setHour(h);}
// if statement which prevents negative hours from being inputted
if (h<HOUR_MIN) {
throw new IllegalArgumentException("Invalid input. No negative hours");
}
}
public void incrementMinutesBy(int minutes) {
int m = getMinutes()+minutes;
m++;
if (m > MINUTES_MAX) {
m%=TOTAL_NUMBERS_MINUTES;
setMinutes(m);
}
if (m<MINUTES_MIN) {
throw new IllegalArgumentException("Invalid input. No negative minutes");
}
else
{
System.out.println("Minutes are: "+m);
}
}
public static void main(String args[])
{
DigitalClock obj=new DigitalClock(12, 15);
obj.incrementHoursBy(HOUR_MAX);
obj.incrementMinutesBy(MINUTES_MAX);
DigitalClockFormatter();
}
public static void DigitalClockFormatter() {
// method for class DigitalClockFormatter
}
}
To simplify the implementation, it's beter to save totalMinutes internaly, but not the separate hours and minutes.
public final class DigitalClock {
private static final int MINUTES_PER_HOUR = (int)TimeUnit.HOURS.toMinutes(1);
private static final int MINUTES_PER_DAY = (int)TimeUnit.DAYS.toMinutes(1);
private int totalMinutes;
public DigitalClock(int hour, int minutes) {
setHour(hour);
setMinutes(minutes);
}
public int getHour() {
return totalMinutes / MINUTES_PER_HOUR;
}
public int getMinutes() {
return totalMinutes % MINUTES_PER_HOUR;
}
public void setHour(int hour) {
if (hour < 0 || hour > 23)
throw new IllegalArgumentException("'hour' should be within [0;23]");
totalMinutes = (int)TimeUnit.HOURS.toMinutes(hour) + getMinutes();
}
public void setMinutes(int minutes) {
if (minutes < 0 || minutes > 59)
throw new IllegalArgumentException("'minutes' should be within [0;59]");
totalMinutes = (int)TimeUnit.HOURS.toMinutes(getHour()) + minutes;
}
public void incrementHoursBy(int hour) {
totalMinutes = withinDay((int)TimeUnit.HOURS.toMinutes(hour) + totalMinutes);
}
public void incrementMinutesBy(int minutes) {
totalMinutes = withinDay(totalMinutes + minutes);
}
private static int withinDay(int totalMinutes) {
totalMinutes %= MINUTES_PER_DAY;
if (totalMinutes < 0)
totalMinutes = MINUTES_PER_DAY + totalMinutes;
return totalMinutes;
}
#Override
public String toString() {
return String.format("%02d:%02d", getHour(), getMinutes());
}
}
I believe that your calculations can also be achieved by subtraction. Consider the following example.
If currentHour is 23 and you add two hours, then the result should be 1 (one).
23 + 2 = 25
25 % 24 = 1
25 - 24 = 1
Similarly for currentMinutes. However, for currentMinutes you also need to increment currentHour if the result of the increment (to currentMinutes) is greater than MINUTES_MAX. And when you increment currentHour you also need to check whether the incremented currentHour value is greater than HOUR_MAX. In other words, if currentHour is 23 and currentMinutes is 55 and you incrementMinutesBy(10), then:
55 + 10 = 65
65 - 60 = 5
Therefore currentMinutes is set to 5 and currentHour needs to be incremented. Therefore:
23 + 1 = 24
24 - 24 = 0
So currentHour needs to be set to 0 (zero).
Also, as explained in the book Java by Comparison, methods need to fail fast so the first thing you should do in both method incrementHoursBy and method incrementMInutesBy is to check the value of the method argument – and not the result of the calculation. After all, you wrote in the code comments that the pre-condition is that the method argument not be negative – even though I think it would be logical to be able to set the digital clock backwards. I mean that's what you do when daylight saving ends and the clocks get turned back one hour. But then again, with your [digital] clock, you could achieve the same result by invoking incrementHoursBy(HOUR_MAX)
Consider the following code:
public class DigitalClock {
private int currentHour;
private int currentMinutes;
public int getHour() {
return currentHour;
}
public void setHour(int currentHour) {
this.currentHour = currentHour;
}
public int getMinutes() {
return currentMinutes;
}
public void setMinutes(int currentMinutes) {
this.currentMinutes = currentMinutes;
}
public static final int HOUR_MAX = 23; // Refactored hourly max
public static final int HOUR_MIN = 0; // Refactored hourly min
public static final int MINUTES_MAX = 59; // Refactored minute max
public static final int MINUTES_MIN = 0; // Refactored minute min
public static final int TOTAL_NUMBERS_HOURS = 24;
public static final int TOTAL_NUMBERS_MINUTES = 60;
/**
* Creates a new digital clock with the time set at the given hours and minutes.
*
* #precondition 0 <= hour <= 23 AND 0 <= minutes <= 59
* #postcondition getHour()==hour AND getMinutes()==minutes
*
* #param hour the hour to set for the time
* #param minutes the minutes to set for the time
*/
public DigitalClock(int hour, int minutes) {
// enforcing hourly preconditions using appropriate ranges
if (hour >= HOUR_MIN && hour <= HOUR_MAX) {
currentHour = hour;
}
else {
currentHour = 0;
// throw an exception on invalid hour's input
throw new IllegalArgumentException("Invalid input for Hours");
}
// enforcing minute preconditions using appropriate ranges
if (minutes >= MINUTES_MIN && minutes <= MINUTES_MAX) {
currentMinutes = minutes;
}
else {
currentMinutes = 0;
// throw an exception on invalid minute's input
throw new IllegalArgumentException("Invalid input for Minutes");
}
}
/**
* Advances the entire clock by the given number of hours. If the hours advances
* past 23 they wrap around.
*
* #precondition hours >= 0
* #postcondition the clock has moved forward by the appropriate number of hours
*
* #param hours the number of hours to add
*/
public void incrementHoursBy(int hour) {
// if statement which prevents negative hours from being inputted
if (hour < HOUR_MIN || hour > HOUR_MAX) {
throw new IllegalArgumentException("Invalid input. Between 0 & 23");
}
int h = currentHour + hour;
// if statement enforcing precondition
if (h > HOUR_MAX) {
h -= TOTAL_NUMBERS_HOURS;
}
// increasing this.hours by the parameter
setHour(h);
}
public void incrementMinutesBy(int minutes) {
if (minutes < MINUTES_MIN || minutes > MINUTES_MAX) {
throw new IllegalArgumentException("Invalid input. Between 0 & 59");
}
int m = getMinutes() + minutes;
if (m > MINUTES_MAX) {
incrementHoursBy(1);
m -= TOTAL_NUMBERS_MINUTES;
setMinutes(m);
}
}
public static void main(String args[]) {
DigitalClock obj = new DigitalClock(22, 55);
obj.incrementHoursBy(1);
obj.incrementMinutesBy(10);
DigitalClockFormatter(obj);
}
public static void DigitalClockFormatter(DigitalClock dc) {
System.out.printf("%02d:%02d", dc.getHour(), dc.getMinutes());
}
}
Running above code displays:
00:05
Alternatively, you could use the date-time API.
import java.time.LocalTime;
public class DigiClok {
private LocalTime clock;
public DigiClok(int hour, int minute) {
clock = LocalTime.of(hour, minute); // throws java.time.DateTimeException if invalid arguments
}
public int getHour() {
return clock.getHour();
}
public void setHour(int currentHour) {
// class 'java.time.LocalTime' is immutable.
int minute = clock.getMinute();
clock = LocalTime.of(currentHour, minute);
}
public int getMinutes() {
return clock.getMinute();
}
public void setMinutes(int currentMinutes) {
int hour = clock.getHour();
clock = LocalTime.of(hour, currentMinutes);
}
public boolean equals(Object obj) {
boolean equal = this == obj;
if (!equal) {
if (obj instanceof DigiClok) {
DigiClok other = (DigiClok) obj;
equal = clock.equals(other.clock);
}
}
return equal;
}
public int hashCode() {
return clock.hashCode();
}
public String toString() {
return clock.toString();
}
public void incrementHoursBy(int hour) {
clock = clock.plusHours(hour); // also handles negative 'hour'
}
public void incrementMinutesBy(int minutes) {
clock = clock.plusMinutes(minutes); // also handles negative 'minute'
}
public static void main(String[] args) {
DigiClok obj = new DigiClok(22, 55);
obj.incrementHoursBy(1);
obj.incrementMinutesBy(10);
System.out.println(obj);
}
}
First of all, I have read this question which i am aware is dealing with the same fundamental problem I am having.
Nevertheless, I am unable to apply the solution to my own particular problem.
in the following example i have a few overloaded Clock constructors. The error occurs in the case where I am trying to create a Clock from string input.
Does anyone have any tips for the correct implementation of the constructor call?
Code:
public class Clock
{
public static void main(String[] args)
{
Clock testClock = new Clock(153, 26);
System.out.println("Input: Clock(153, 26)");
System.out.println(testClock.toString());
Clock testClock2 = new Clock(9000);
System.out.println("Input: Clock(9000)");
System.out.println(testClock2.toString());
Clock testClock3 = new Clock(23:59);
System.out.println("Input: Clock(23:59)");
System.out.println(testClock3.toString());
System.out.println("Input: testClock2.add(20)");
System.out.println(testClock2.add(20));
System.out.println("input: testClock.add(testClock2)");
System.out.println(testClock.add(testClock2).toString());
}
// Constructors
public Clock(int min, int h)
{
this.min += min%60;
h += min/60;
this.h += h%24;
}
public Clock(int min)
{
this.min += min%60;
this.h += (min/60)%24;
}
public Clock (String theTime)
{
int minutes = Integer.parseInt(theTime.substring(0,1));
int hours = Integer.parseInt(theTime.substring(3,4));
Clock stringClock = new Clock(minutes, hours);
return stringClock; //error occurs *********************
}
private int h;
private int min;
public int getMin() {
return min;
}
public int getH() {
return h;
}
public Clock add(int min)
{
int newMin = this.min + min;
int newH = this.h;
Clock newClock = new Clock(newMin, newH);
return newClock;
}
public Clock add(Clock c)
{
int newMin = this.min + c.min;
int newH = this.h + c.h;
Clock newClock = new Clock(newMin, newH);
return newClock;
}
public String toString()
{
String theTime = "";
if (this.h < 10)
{
theTime += "0" + this.h;
}
else
{
theTime += this.h;
}
theTime += ":";
if (this.min < 10)
{
theTime += "0" + this.min;
}
else
{
theTime += this.min;
}
return theTime;
}
}
You could call this but it should be very first statement such as:
public Clock (String theTime)
{
this(
Integer.parseInt(theTime.substring(0,1)),
Integer.parseInt(theTime.substring(3,4))
);
}
Alternatively you could use a static factory method:
public static Clock parseHHMM(String theTime)
{
int hh = Integer.parseInt(theTime.substring(0,1));
int mm = Integer.parseInt(theTime.substring(3,4));
return new Clock(hh, mm);
}
I prefer the latter, it is common approach in Java, e.g. here.
There is also a problem with that line:
Clock testClock3 = new Clock(23:59);
If you want the argument to be treated as String, you should surround the value passed as argument with quotes, like this:
Clock testClock3 = new Clock("23:59");
, because when you don't change the look of parameter passed, it won't compile.
You could consider splitting theTime at the semicolon":" so as to obtain an array of two integers, the first being the hour and the second being the minutes. Take a look
public Clock (String theTime)
{
this(Integer.parseInt(theTime.split(":")[1],
Integer.parseInt(theTime.split(":")[0]);
}
hope this helps
I'm creating a four digit class (like a clock) while calling methods from a two digit class.
The four digit class has two segments. When segment one reaches my set maximum value, the second segment must increase by one.
these are my methods from my first class:
/*
* method to set the value
*/
public void setValue(int anyValue){
if((anyValue < TOO_HIGH) && (anyValue >= 0)){
value = anyValue;}
}
/*
* method to set the value plus one
*/
public void setValuePlusOne(){
int tempValue = value + 1;
if(tempValue < TOO_HIGH){
value = tempValue;}
else{
value = 0;
// value = tempValue % TOO_HIGH;}
}
This is from my second four digit class.
/*
* method to set the increment
*/
public void setIncrement(int increment){
rightSegment.setValuePlusOne();
if(increment == 0)
leftSegment.setValuePlusOne();
}
I think there might be something wrong with my increment == 0. It doesn't compile when I try
if(rightsegment.setValuePlusOne()==0)
any advise would help. Thank you!!
setValuePlusOne(...) does not return anything. Call setValuePlusOne before the if and then use (rightsegment.getValue() == 0) for the if.
Please try the code below. Hope the below code will help you to achieve your implementation.
Instead of setting the TOO_HIGH integer value in the if else block of the below given code, you can set it in the RightSegment and LeftSegment classes respectively which is extending the Clock class.
Thanks
package stackoverflow;
public class Clock {
private int value;
private int TOO_HIGH;
private Clock rightSegment;
private Clock leftSegment;
/*
* method to set the value
*/
public void setValue(int anyValue, String position){
if(position.equals("right")){
TOO_HIGH = 60;
}else if(position.equals("left")){
TOO_HIGH = 13;
}
if((anyValue < TOO_HIGH) && (anyValue >= 0)){
value = anyValue;}
}
/*
* method to set the value plus one
*/
public void setValuePlusOne(){
int tempValue = value + 1;
if(tempValue < TOO_HIGH){
value = tempValue;}
else{
value = 0;
}
// value = tempValue % TOO_HIGH;}
}
/*
* method to set the i`ncrement
*/
public void setIncrement(int increment, Clock right, Clock left){
rightSegment = right;
leftSegment = left;
//rightSegment = new Clock();
//leftSegment = new Clock();
rightSegment.setValuePlusOne();
if(increment == 0){
leftSegment.setValuePlusOne();
}
}
public static void main (String args[]){
Clock clock = new Clock();
clock.rightSegment = new Clock();
clock.leftSegment = new Clock();
clock.rightSegment.setValue(12, "right");
clock.leftSegment.setValue(12, "left");
clock.rightSegment.setIncrement(0, clock.rightSegment, clock.leftSegment);
System.out.println("Time "+clock.leftSegment.value+":"+clock.rightSegment.value);
}
}
I'm not sure why this occurs, but the 60th minute gets printed in the results when it should change to hour after minute 59.
Here is my class and main program:
public class Main {
public static void main(String[] args) {
BoundedCounter minutes = new BoundedCounter(59);
BoundedCounter hours = new BoundedCounter(23);
int i = 0;
while (i < 121) {
System.out.println(hours + ":" + minutes); // the current time printed
if (minutes.getValue() >= 59) {
hours.getValue();
i++;
}
}
}
//BoundedCounter
public class BoundedCounter {
private int value;
private int upperLimit;
public BoundedCounter(int upperLimit) {
this.upperLimit = upperLimit;
}
public void next() {
if (this.value >= this.upperLimit) {
this.value = 0;
} else {
this.value++;
}
}
public String toString() {
if (this.value < 10) {
return "" + 0 + value;
} else {
return "" + value;
}
}
public int getValue() {
if (this.value <= this.upperLimit) {
return this.value++;
} else {
return this.value = 0;
}
}
}
}
Some results:
01:56
01:57
01:58
01:59
02:60
02:00
02:01
02:02
02:03
02:04
02:05
02:06
02:07
02:08
02:09
02:10
02:11
02:12
02:13
02:14
02:15
02:16
02:17
02:18
02:19
02:20
02:21
02:22
02:23
02:24
02:25
02:26
02:27
02:28
02:29
02:30
02:31
02:32
02:33
02:34
02:35
02:36
02:37
02:38
02:39
02:40
02:41
02:42
02:43
02:44
02:45
02:46
02:47
02:48
02:49
02:50
02:51
02:52
02:53
02:54
02:55
02:56
02:57
02:58
02:59
03:60
03:00
03:01
03:02
03:03
03:04
03:05
i.e. 2:60 and 3:60 are unexpected output
First, your methods are doing what they are not supposed to do. For example, getValue() should only return the value, not increment it. Here is how this can be done:
Main.java
public class Main {
public static void main(String[] args) {
BoundedCounter minutes = new BoundedCounter(59);
BoundedCounter hours = new BoundedCounter(23);
int i = 0;
while (i < 121) {
System.out.println(hours + ":" + minutes);
minutes.next(); // counting minutes
if (minutes.getValue() == 0) { // when minutes==0, count hours
hours.next(); // counting hours
i++;
}
}
}
}
BoundedCounter.java
class BoundedCounter {
private int value;
private int upperLimit;
public BoundedCounter(int upperLimit) {
this.upperLimit = upperLimit;
}
public void next() {
// when reach the upperLimit, the next value should be 0
// so >= is not needed, just == will do
this.value = this.value == this.upperLimit ? 0 : this.value+1;
}
public String toString() {
// using smarter approach to pad with zeros :)
return String.format("%02d", value);
}
public int getValue() {
// this method should only return the value, not change it in any way
return this.value;
}
}
Some outputs:
00:00 00:01 00:02 00:03 00:04 00:05 00:06 00:07 00:08 00:09 00:10
00:11 00:12 00:13 00:14 00:15 00:16 00:17 00:18 00:19 00:20 00:21
00:22 00:23 00:24 00:25 00:26 00:27 00:28 00:29 00:30 00:31 00:32
00:33 00:34 00:35 00:36 00:37 00:38 00:39 00:40 00:41 00:42 00:43
00:44 00:45 00:46 00:47 00:48 00:49 00:50 00:51 00:52 00:53 00:54
00:55 00:56 00:57 00:58 00:59 01:00 01:01 01:02 01:03 01:04 01:05
01:06 01:07 01:08 01:09 01:10 01:11 01:12 01:13 01:14 01:15 01:16
01:17 01:18 01:19 01:20 01:21 01:22 01:23 01:24 01:25 01:26 01:27
01:28 01:29 01:30 01:31 01:32 01:33 01:34 01:35 01:36 01:37 01:38
01:39 01:40 01:41 01:42 01:43 01:44 01:45 01:46 01:47 01:48 01:49
01:50 01:51 01:52 01:53 01:54 01:55 01:56 01:57 01:58 01:59 02:00
02:01
You should change the lines :
if (this.value <= this.upperLimit) {
return this.value++;
to
if (++this.value <= this.upperLimit) {
return this.value;
AND
if (minutes.getValue() >= 59) {
to
if (minutes.getValue() == 0) {
The problem is that when minutes value is 59 in your code, it is still <= 59, so it gets inside the if block. Then you return 59 to the user and the minutes are now 60.
So, at the next iteration, you first print 60 and then you call the getValue() method, which turns your minutes to 0.
I guess you are having the same problem when the hour turns 24...
Other than that, consider following a more "expected" functionality of your methods, based on their names, which makes it clear what they do and it becomes easier, even for you to debug. See Shadowfax's answer for example.
You aren't showing any part of what actually increments your hours or minutes, but it appears to be a problem in your getValue call.
public int getValue() {
if (this.value <= this.upperLimit) {
return this.value++;
} else {
return this.value = 0;
}
}
That this.value++; part increments value to 60, and does not roll it over.
there is a slight problem in your approach to create a BoundedCounter
you should not change your counter value when your method name says you just want to read it.Second all your condition check to resets should happen inside your BoundedCounter class only.If you want to reset your counter just expose another method to do that.
Here is the working solution for your reference
import java.util.*;
public class Test{
public static void main(String[] args){
BoundedCounter minutes = new BoundedCounter(59);
BoundedCounter hours = new BoundedCounter(23);
int i = 0;
while (i < 121) {
if (minutes.hasNext()) {
minutes.next();
} else {
hours.next();
minutes.resetTo(0);
}
System.out.println(hours + ":" + minutes);
i++;
}
}
}
class BoundedCounter {
private int value;
private int upperLimit;
public BoundedCounter(int upperLimit) {
this.upperLimit = upperLimit;
}
public void next() {
++this.value;
}
public boolean hasNext() {
return this.value < this.upperLimit;
}
public void resetTo(int resetValue) {
this.value = resetValue;
}
public int getValue() {
if (this.hasNext()) {
return this.value;
}
return 0;
}
public String toString() {
if (this.value < 10) {
return "" + 0 + value;
} else {
return "" + value;
}
}
}
"a fourth field to keep track of whether or not the alarm is set; alternatively, you could set the alarm fields to a negative value (-1 is my favorite)." Please help, I am trying to create a field which checks if my method is set. I've tried an if and statement so far but it probably is not the way to go. I need to check that my alarm is set. Probably going to need a return value then right?
public void setAlarm (int hours, int minutes, int seconds)
{
if(hours minutes seconds > 0) {
alarmHour = hours;
alarmMinute = minutes;
alarmSecond = seconds;
}
else {
System.out.println("Please set the alarm.");
}
}
I believe this is what is intended.
private boolean isSet;
public boolean isAlarmSet()
{
return isSet;
}
public void setAlarm (int hours, int minutes, int seconds)
{
alarmHour = hours;
alarmMinute = minutes;
alarmSecond = seconds;
isSet = true;
}