我的主类末尾有以下代码来初始化对象并启动程序:
HumanPlayer humanPlayer = new HumanPlayer(baseHold);
Controller controller = new Controller(new ComputerPlayer(), humanPlayer, new Dice(seed));
controller.start();
在我的Controller类中,是以下代码:
public class Controller
{
int roller;
public Controller(ComputerPlayer cpuPlayer, HumanPlayer userPlayer, Dice dice)
{
}
//....
}
我不确定上面要初始化的内容,因为我已经尝试了一些方法,但是在下面的代码中仍然找不到我的对象骰子:
public void start()
{
for (int count = 0; count < 5; count++)
{
roller = dice.roll();
System.out.println("Die roll: " + roller);
}
}
roll是Dice类中的一种方法。我是否有一种特殊的方式告诉它在控制器对象中而不是在变量中寻找骰子,而不是在控制器对象中寻找变量,还是我要这样做完全是错误的?
我希望能够在此处将骰子滚动5次。
错误:
Controller.java:39: error: cannot find symbol
roller = dice.roll();
^
symbol: variable dice
location: class Controller
1 error
您必须将声明dice
为的实例字段Controller
,如下所示:
public class Controller {
private Dice dice;
// rest of the class code
}
然后在构造函数中,您将执行以下操作:
public Controller(ComputerPlayer cpuPlayer, HumanPlayer userPlayer, Dice dice) {
// some other code
this.dice = dice;
}
然后,您可以this.dice
在Controller
类内的其他方法中使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句