我目前使用Java和Codename One构建了一个2D小行星游戏,主要关注OOP模式。然而,我遇到了麻烦,试图动态地创建新对象(在我的例子中,我想添加的对象是一个超类GameObject)以添加到ArrayList。正如你在GameWorld.java的void init()方法中看到的那样,我创建了一个列表,其中包含包含Asteroids,Ships,Spacestations的子类的GameObject类型。如何在Java中动态创建要添加到ArrayList中的对象
该程序要求在类的命令键盘输入,如'a',然后应该添加一个新的Asteroid(GameObject的子类)对象到ArrayList中。用户应该能够添加尽可能多的Asteroids,因为他们想分配给ArrayList。
我的问题是:我如何做到这一点没有已经宣布了一个名为AsteroidTest型小行星的变量像我当前已经在我的addAsteroid做类游戏世界的()函数?谢谢!
GameWorld.java
package com.mycompany.a1;
import java.util.ArrayList; //For ArrayList Usage
public class GameWorld {
public void init() {
ArrayList<GameObject> list = new ArrayList<GameObject>();
}
//other methods here to manipulate Game objects and data
public void addShip() {
Ship ShipTest = new Ship();
list.add(ShipTest);
System.out.println(ShipTest.getLocation());
}
public void addAsteroid(){
Asteroid AsteroidTest = new Asteroid();
list.add(AsteroidTest);
System.out.println(AsteroidTest.getLocation());
}
public void addSpaceStation(){
}
}
Game.java
package com.mycompany.a1;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.Label;
import com.codename1.ui.TextField;
import com.codename1.ui.events.ActionEvent;
import java.lang.String;
import com.codename1.ui.Form;
public class Game extends Form{
private GameWorld gw;
public Game(){
gw = new GameWorld();
gw.init();
play();
}
private void play(){
Label myLabel=new Label("Enter a Command:"); this.addComponent(myLabel);
final TextField myTextField=new TextField();
this.addComponent(myTextField);
this.show();
myTextField.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
String sCommand=myTextField.getText().toString();
myTextField.clear();
switch (sCommand.charAt(0)){
case 's':
gw.addShip();
break;
case 'a':
gw.addAsteroid();
break;
case 'b':
gw.addSpaceStation();
break;
//add code to handle rest of the commands
} //switch
} //actionPerformed
} //new ActionListener()
); //addActionListener
} //play
//code to enter text field and receive keyboard input
}
GameObject.java超类。子类包括小行星,船,飞弹,将SpaceStation
package com.mycompany.a1;
public abstract class GameObject {
private double x;
private double y;
public GameObject(){
x = 0;
y = 0;
}
public double getX(){
return x;
}
public void setX(double newX){
x = newX;
}
public double getY(){
return y;
}
public void setY(double newY){
y = newY;
}
public String getLocation(){
return "(" + x + ", " + y + ")";
}
}
Asteroid.java
package com.mycompany.a1;
import java.util.Random;
public class Asteroid extends MovableObject {
private Random rand = new Random();
public Asteroid() {
setX(rand.nextInt(1023) + rand.nextDouble());
setY(rand.nextInt(767) + rand.nextDouble());// TODO Auto-generated
constructor stub
}
}
'list.add(新小行星())更清晰;' –
@KevinAnderson哇真的那么简单吗?我也得到ArrayList列表变量的错误。错误说“局部变量列表的值未被使用”。 –
应该说'list'没有被定义。你在'init()'方法的本地定义了'list',但是这个定义在'init()'之外是不可见的。你希望'list'被定义为你类的成员变量。如果你不明白为什么,你需要研究的主题是“变量的范围”。 –