我目前使用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'被定義爲你類的成員變量。如果你不明白爲什麼,你需要研究的主題是「變量的範圍」。 –