gpt4 book ai didi

java - 如何对二维数组的元素使用方法?

转载 作者:行者123 更新时间:2023-12-02 04:52:27 25 4
gpt4 key购买 nike

如何对二维数组的元素使用方法?

我有一个类board,并初始化了一个cell类型的二维数组。本质上,我想使用单元格元素,并使用该类中的方法。但是,我不确定如何实现它,因为当我尝试时出现错误

board[1][1].cellmethod()

董事会代码:

public class Board {
private int col = 1, row= 1;
private cell[][] board;
private RandomNumberGenerator rand = new RandomNumberGenerator();


public Board(){
board = new cell[col][row];
//Initialize board with cells
for (int r = 0 ; r<=row; r++){
for(int c = 0; c<= col; c++){
board[c][r] = new cell(rand.getRandIntBetween(1,6), translateOffsetToPixel(c,r).getX(), translateOffsetToPixel(c,r).getY());
}
}
}

细胞类别

public class cell {
//which shape the cell will consist
private int shape;

//offset of where the cell is located by cell number -> need to translate the given coordinates to pixel
private int x, y;

private int SHAPE_WIDTH = 50; //Width of each shape (pixels)
private int SHAPE_HEIGHT = 50; //Height of each shape (pixels)

private Rect rect;
private boolean visible;

public cell(int shape, int x, int y){
this.shape = shape;
this.x = x;
this.y = y;
rect = new Rect( x, y, x + SHAPE_WIDTH, y + SHAPE_HEIGHT);
visible = false;
}

public int getX() {return x;}
public int getY() {return y;}
public int getShape() {return shape;}



}

我在哪里调用董事会对象

public class PlayState extends State{
private Board board;


@Override
public void init() {
board = new Board();

}

@Override
public void update(float delta) {

}

@Override
public void render(Painter g) {
for(int r = 0; r<=board.getRow(); r++){
for(int c = 0; c<=board.getCol(); c++){
board[0][0]. // ERROR, can't implement any cell methods
}
}

}

最佳答案

您的 board 数组的大小为一(行和列)。

private int col = 1, row= 1;

因此,您的 boardboard[0][0] 处只有一个可用元素,即第一行和第一列。访问 board[1][1] 因此会抛出 ArrayIndexOutOfBoundsException

请记住,array 索引的最大值仅为 array.length - 1

<小时/>

在您的实际实现中

board = new Board();

board 不是数组;它是一个 Board 对象。因此,显然您无法使用索引 [][] 访问它。您需要通过 getter 方法公开底层的 board[][]

public cell[][] getBoard() {
return board;
}

然后您可以在 render() 方法中使用 getter 作为

@Override
public void render(Painter g) {
cell[][] boardArr = board.getBoard();
for(int r = 0; r<=board.getRow(); r++){
for(int c = 0; c<=board.getCol(); c++){
boardArr[r][c].cellMethod();
}
}
}

关于java - 如何对二维数组的元素使用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29091544/

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