我目前正在学习书中的一些练习,任务之一是:编写一个骰子类“ Dice”,其值在1-6之间。还应该有一个选择一个随机值的构造函数,以及一个也选择一个随机值的roll()方法。还应该创建方法getValue(),该方法将用于检索显示的值。为此程序编写一个测试类。
编辑*我将随机化器移至构造函数,而将roll方法留空。构造函数已经随机化后,我应该在roll()方法中做什么?
到目前为止,这是我的代码:
public class Dice {
int value;
int currentRoll;
public Dice() {
Random rand = new Random();
this.value = 1;
this.currentRoll = rand.nextInt(6) + 1;
}
public int roll() {
Random rand = new Random();
this.currentRoll = rand.nextInt(6) + 1;
return this.currentRoll;
}
public int getValue() {
return this.currentRoll;
}
}
我不明白的是:为什么要同时在构造函数和roll()方法中将值随机化?另外,我错过了什么?
答案 0 :(得分:2)
为什么要在构造函数中选择一个随机值?好吧,坦率地说,因为这是练习的要求。
他们为什么有这个要求?如果我不得不猜测,这是为了模拟以下事实:无论是否显式滚动模具,模具总是会面朝上(即具有值),但是如果您想要确定的答案,则可以d必须询问这本书的作者他/她的想法。
您可以通过在构造函数中调用-j
来实现。另外,请注意,已初始化但从未使用过的roll
成员具有冗余性:
value
答案 1 :(得分:0)
要求是构造函数和roll()
方法都选择一个随机值。他们做同样的事情。因此,为了避免不必要的代码重复,构造函数可以例如调用roll方法。
警告:在构造函数中放置对可重写方法的调用是坏习惯。 This post explains为什么。
您的代码可能如下所示:
class Dice {
private int value;
// You could create the Random instance here once, instead of everytime
// recreating it
private Random r = new Random();
public Dice() {
roll();
}
// You could also change the return type to and int and return this.value
public final void roll() {
this.value = this.r.nextInt(6) + 1;
}
public int getValue() {
return this.value;
}
}
我不知道我是否完全同意这些要求,但是由于它们是要求,因此您应该承认它们。