我有一个任务,我将使用JavaFX创建一个滑槽和梯子游戏。
我目前所坚持的是,一旦用户选择了他们想要的玩家数量,我运行的方法就会推错。
我已通过调试器运行它,我知道问题是什么行,但我不知道从哪里开始。
例外是:
线程中的异常" JavaFX应用程序线程" java.lang.ArrayIndexOutOfBoundsException:0
我发现如果我将private Players [] players = new Players[0];
中的零更改为4,则可以正常工作。但是,如果我尝试更改private Circle [] c = new Circle[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);
}
}
答案 0 :(得分:0)
你正在将玩家和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);
}
...
}