我正在研究mooc.fi的作业,我真的陷入了时钟任务。我不想要一个解决方案,但建议如何在我学习的时候找到我的解决方案,并且真的需要弄清楚如何解决这个问题。如果您不熟悉mooc,则当前部分介绍如何使用对象中的对象。
它由三个类组成,主要创建时钟,boundedcounter是时钟滴答的原因。我将它打印到屏幕上,但是当输入自定义启动输入时,它首先打印,然后将值重置为零。有人能指出我正确的方向吗?对不起基本问题,仍在尝试学习这种java语言!
主要
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++;
}
}
}
时钟
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;
}
}
答案 0 :(得分:0)
BoundedCounter.next()
不小于value
, value
会将upperLimit
设置为0。由于Clock
构造函数始终将所有BoundedCounter
value
值初始化为等于 upperLimit
,因此对Clock.tick()
的第一次调用将导致所有BoundedCounter
个对象将其value
值设置为0。
答案 1 :(得分:0)
您将当前时间传递给BoundedCounter。
this.hours = new BoundedCounter(hoursAtBeginning);
this.minutes = new BoundedCounter(minutesAtBeginning);
this.seconds = new BoundedCounter(secondsAtBeginning);
但是BoundedCounter期待上限,而不是当前时间。
public BoundedCounter(int upperLimit) {
因为你传递的时间被认为是上限,下一个滴答将翻到0:0:0。
答案 2 :(得分:0)
除了更正:
this.hours = new BounedCounter(int upperLimit);
this.minutes = new BounedCounter(int upperLimit);
this.seconds = new BounedCounter(int upperLimit);
方法public void tick()
必须如下所示组成,否则当分钟的值为00而秒的值为01,02,... 59时,小时的值将为每秒增加,结果为01:00:01,2:00,2:00,03等等。
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();
}
}