gpt4 book ai didi

Javafx 为滑道和梯子创建玩家和组件

转载 作者:太空宇宙 更新时间:2023-11-04 12:39:39 25 4
gpt4 key购买 nike

我有一个任务,要使用 JavaFX 创建一个滑槽和梯子游戏。

我目前遇到的问题是,一旦用户选择了他们想要的玩家数量,我运行的方法就会出现错误。

我已经通过调试器运行了它,我知道哪一行出了问题,但我不知道从这里去哪里。

异常(exception)情况是:

Exception in thread "JavaFX Application Thread" java.lang.ArrayIndexOutOfBoundsException: 0

我发现,如果我将 private Players []players = new Players[0]; 中的零更改为 4,它就可以工作。但是,如果我尝试更改 private Circle [] c = new Circle[0];

中的 0,我会收到另一个错误
public class Main extends Application {
private final int BOARD_DIM = 10;
private Players [] players = new Players[0];
private Circle [] c = new Circle[0];

public static void main(String[]args){
launch();
}

public void start(Stage pStage) throws Exception{
//ROOT PANE
BorderPane root = new BorderPane();

//MENUBAR

//BOARD CREATION

//PLAYER SELECTION/RESUME PREVIOUS GAME
//Drop down menu
HBox players = new HBox();
Label intro = new Label("Select # of players");
ChoiceBox<String> p = new ChoiceBox<>();
p.getItems().addAll("2","3","4");
p.setPadding(new Insets(6));
//Button to start new game
Button startGame = new Button("Start Game");
startGame.setOnAction(e -> getChoice(p));
startGame.setPadding(new Insets(10));
players.getChildren().addAll(intro,p,startGame);
root.setRight(players);

Scene scene = new Scene(root, 900, 650);
pStage.setTitle("Chutes and Ladders");
pStage.setScene(scene);
pStage.show();
}
private void getChoice(ChoiceBox<String> p) {
int numOfPlayers = Integer.parseInt(p.getValue());
for(int i = 0; i < numOfPlayers; i++){
players[i] = new Players("p"+(i+1),9,0, false);
c[i] = new Circle(25);
}
c[0].setFill(Color.GREEN);
c[1].setFill(Color.YELLOW);
if(numOfPlayers >= 3){
c[2].setFill(Color.RED);
}
if(numOfPlayers == 4){
c[3].setFill(Color.BLACK);
}
}

最佳答案

您将players 和c 初始化为长度为0 的数组。在循环中,您将迭代从0 到numOfPlayers 的元素。这就是导致异常的原因。

首先声明你的数组:

private Players [] players;
private Circle [] c;

然后在您的方法中,用您需要的长度初始化数组(如果您稍后需要更改长度,我建议切换到 ArrayList)。

private void getChoice(ChoiceBox<String> p) {
int numOfPlayers = Integer.parseInt(p.getValue());
c = new Circle[numOfPlayers]; //add these lines
players = new Players[numOfPlayers]; //add these lines
for(int i = 0; i < numOfPlayers; i++){
players[i] = new Players("p"+(i+1),9,0, false);
c[i] = new Circle(25);
}
...
}

关于Javafx 为滑道和梯子创建玩家和组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36948306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com