我正在做一个过去的学校工作,它是关于微波应用程序与儿童班,时钟。不知怎的,有些人,我对我的代码感到困惑,完全迷失了。有人可以帮我这些吗?谢谢!
首先是Clock类。
class Clock extends Microwave {
private int hour;
private int minute;
private int second;
Clock()
{
hour = 0;
minute = 0;
second = 0;
}
Clock(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
}
public int getHour()
{
return hour;
}
public int getMin()
{
return minute;
}
public int getSec()
{
return second;
}
public String toString()
{
return (String.valueOf(second));
}
protected void tick()
{
second++;
if(hour == 23 && minute == 59 && second == 59)
{
hour = 0;
minute = 0;
second = 0;
} else if(minute == 59 && second == 59)
{
hour++;
minute = 0;
second = 0;
} else if(second == 59)
{
minute++;
second = 0;
}
}
}
接下来将是父类,微波。
class Microwave {
private int maxPower;
private int currentPower;
private Clock theClock;
Microwave()
{
maxPower = 500;
currentPower = 500;
theClock = new Clock();
}
Microwave(int maxp, Clock theClock)
{
maxPower = maxp;
currentPower = maxPower;
theClock = new Clock();
}
public int getCurrentPower()
{
return currentPower;
}
public int getMaxPower()
{
return maxPower;
}
public String getTime()
{
return "The time is " + theClock.getHour() + ":" + theClock.getMin() + ":" + theClock.getSec();
}
protected void cook(int p, int t)
{
if(p < maxPower)
{
currentPower = p;
} else
{
System.exit(0);
}
for(int i = 0; i < t; i++)
{
theClock.tick();
}
}
}
最后,主要方法类。
class TestMicrowave
{
public static void main(String []args)
{
Clock c = new Clock(14, 30,30);
Microwave m = new Microwave(750, c);
System.out.println("The microwave is currently at " +
m.getCurrentPower() + " watts and "+ m.getTime());
m.cook(600,45); // should advance time to 14:31:15
System.out.println(m.getTime());
m.cook(800,45); // shoudln't cook as power > maxPower
System.out.println(m.getTime());
}
}
我认为,我在Microwave类中的getTime()方法有问题,但我不知道它有什么问题。 提前谢谢!
答案 0 :(得分:6)
时钟不是儿童班。微波炉是一个时钟的组成部分。从Clock类中删除'extends Microwave'。
此设计中不应有任何继承。
答案 1 :(得分:2)
继承建议是垃圾,你应该改为编写时钟(微波可能包含一个时钟,因为你的微波类已经写好了),所以从你的Clock类中删除extends Microwave
。
除非这个问题,另一个问题是你的CTOR:
Microwave()
{
maxPower = 500;
currentPower = 500;
theClock = new Clock();
}
Microwave(int maxp, Clock theClock)
{
maxPower = maxp;
currentPower = maxPower;
//theClock = new Clock(); // you're passing a reference to this already, so by using this call you replace it with a new instance via the default ctor of Clock().
this.theClock = theClock;
}
答案 2 :(得分:1)
接受Clock
参数的构造函数正在丢弃它,因此您总是以零时钟开始。
Microwave(int maxp, Clock clock)
{
maxPower = maxp;
currentPower = maxPower;
this.theClock = clock;
}