java - How do use methods for the elements of a 2d array? -
how use methods elements of 2d array?
i have class board, , initialized 2d array type cell. essentially, want use cell elements, , use methods class. however, unsure how implement that, because error when try
board[1][1].cellmethod() code board:
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 cells (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()); } } } cell class
public class cell { //which shape cell consist private int shape; //offset of cell located cell number -> need translate given coordinates 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;} } where call board object
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 cell methods } } }
your board array of size 1 (row , column).
private int col = 1, row= 1; so, board has 1 element available @ board[0][0], first row , first column. accessing board[1][1] hence throws arrayindexoutofboundsexception.
remember array index can have maximum value of array.length - 1 only.
in actual implementation
board = new board(); board not array; it's board object. so, can't access indices [][]. need expose underlying board[][] through getter method.
public cell[][] getboard() { return board; } then can use getter in render() method as
@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(); } } }
Comments
Post a Comment