我在无参数构造函数SandBox sb
中创建了AsteroidGame()
,但是当我尝试向sb
添加对象时,在我的generate方法中找不到变量SandBox
。对我要去哪里错有任何见解吗?
public static void main(String[] args)
{
new AsteroidGame();
}
public AsteroidGame()
{
//Create SandBox
SandBox sb = new SandBox();
sb.init(this);
}
public void generate()
{
//Instantiate Rocket and add it to Sandbox
Dimension dime = sb.getPanelBounds();
Rocket rock = new Rocket(dime.width/2, dime.height/2);
sb.addBlob(rock);
}
最佳答案
您可以这样做Declare SandBox as instance/class variable
:
SandBox sb; // Declare SandBox as instance/class variable
public static void main(String[] args)
{
new AsteroidGame();
}
public AsteroidGame()
{
//Create SandBox
sb = new SandBox();
sb.init(this);
}
public void generate()
{
//Instantiate Rocket and add it to Sandbox
Dimension dime = sb.getPanelBounds();
Rocket rock = new Rocket(dime.width/2, dime.height/2);
sb.addBlob(rock);
}
或
Create a new local variable in
generate()method:
public static void main(String[] args)
{
new AsteroidGame();
}
public AsteroidGame()
{
//Create SandBox
SandBox sb = new SandBox();
sb.init(this);
}
public void generate()
{
// Create a new local variable here
SandBox sb = new SandBox();
Dimension dime = sb.getPanelBounds();
Rocket rock = new Rocket(dime.width/2, dime.height/2);
sb.addBlob(rock);
}
关于java - 生成方法未识别变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28935409/