在另一个对象中引用对象实例
Reference object instance inside of another object
我的主 class 末尾有以下代码来初始化对象并启动程序:
HumanPlayer humanPlayer = new HumanPlayer(baseHold);
Controller controller = new Controller(new ComputerPlayer(), humanPlayer, new Dice(seed));
controller.start();
在我的控制器 class 中,是以下代码:
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 class 中的一个方法。
有什么特别的方法可以告诉它在我的控制器对象中查找骰子作为对象而不是在我的控制器对象中查找变量,还是我这样做完全错了?
我希望能够在这里掷骰子 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;
}
然后就可以在Controller
里面的其他方法中使用this.dice
class.
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();
我的主 class 末尾有以下代码来初始化对象并启动程序:
HumanPlayer humanPlayer = new HumanPlayer(baseHold);
Controller controller = new Controller(new ComputerPlayer(), humanPlayer, new Dice(seed));
controller.start();
在我的控制器 class 中,是以下代码:
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 class 中的一个方法。 有什么特别的方法可以告诉它在我的控制器对象中查找骰子作为对象而不是在我的控制器对象中查找变量,还是我这样做完全错了?
我希望能够在这里掷骰子 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;
}
然后就可以在Controller
里面的其他方法中使用this.dice
class.
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();