我的任务是使用JavaFX创建滑道和梯子游戏。

我目前坚持的是,一旦用户选择了他们想要的玩家数量,我运行的方法就会出错。

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

例外是:


  线程“ JavaFX应用程序线程”中的异常
  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);
        }
}

最佳答案

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

首先只需声明您的数组:

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


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

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);
    }
    ...
}

关于java - Javafx为滑道和梯子创建播放器和棋子,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36948306/

10-13 09:12