我在主类末尾有以下代码来初始化对象并启动程序:
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
答案 0 :(得分:1)
您必须将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
。
答案 1 :(得分:0)
HumanPlayer humanPlayer = new HumanPlayer(baseHold);
Controller controller = new Controller(new ComputerPlayer(), humanPlayer new Dice(seed));
controller.start();
humanPlayer
和new Dice(seed)
HumanPlayer humanPlayer = new HumanPlayer(baseHold);
Controller controller = new Controller(new ComputerPlayer(), humanPlayer, new Dice(seed));
controller.start();