我有一个Class代表一个星球上的不同资源。从类实例化对象后,该对象应以恒定速率增加资源数量。生产率存储在变量中,可以更改。我希望在改变生产率之后,实际的资源生产速率也会改变。这是我的参考资料课:
public class PlanetResources implements ResourceObserver {
//baseProducingRate;
private final int SECONDSINHOUR =3600;
private final int mmBaseProducingRate =20;
private final int cBaseProducingRate = 15;
private final int dBaseProducingRate = 13;
private final int vBaseProducingRate = 15;
//Amount of resources of each type
private int metallicMicrolattice;
private int energy;
private int carbyne;
private int deuterium;
private int vibranium;
//Resources Producing rate
private int mmProducingRate=this.mmBaseProducingRate;
private int cProducingRate= this.cBaseProducingRate;
private int dProducingRate = this.dBaseProducingRate;
private int vProducingRate = this.vBaseProducingRate;
public PlanetResources(int mm, int e, int c, int d, int v) {
super();
this.metallicMicrolattice = mm;
this.energy = e;
this.carbyne = c;
this.deuterium = d;
this.vibranium = v;
int delay=2000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
metallicMicrolattice++;
}
}, delay, this.SECONDSINHOUR*1000/this.getMmProducingRate());
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
carbyne++;
}
}, delay, this.SECONDSINHOUR*1000/this.cProducingRate);
}
这是我的测试代码:
public static void main(String args[]) throws InterruptedException
{
PlanetResources thePlanetResource = new PlanetResources(0, 0, 0, 0, 0);
Scanner keyboard= new Scanner(System.in);
while(true)
{
System.out.println("Welcome, What would you like to do ?");
System.out.println("1) visit ship Yard");
System.out.println("2) visit mines");
System.out.println("3) manage fleet");
System.out.println("4) explore galaxy");
System.out.println("5) exit");
int option = keyboard.nextInt();
if (option==2)
{
System.out.println("Here are your current resources:");
System.out.println(thePlanetResource);
Thread.sleep(10000);
System.out.println(thePlanetResource);
thePlanetResource.setMmProducingRate(10000);
}
}
当我运行它时,我得到:
在提供的选项中第二次选择2(10000 /小时)后,metallicMicrollatice的值应增加得更快。但是10秒钟后它仍然只产生1。