mau*_*iii 4 java random for-loop initialization arraylist
我正在为折叠游戏制作2D Arraylist板,但现在只是做一个文本表示.我创建了这个板,但是当我尝试用randomChar()填充它时,所有的行都得到相同的随机字符.我究竟做错了什么?
public static void createBoard(int rSize, int cSize) {
ArrayList<Character> row = new ArrayList<Character>();
ArrayList<ArrayList<Character>> board = new ArrayList<ArrayList<Character>>();
for (int c = 0; c < cSize; c++) {
board.add(row);
}
for (int r = 0; r < rSize; r++) {
board.get(r).add(randomChar());
//row.add(randomChar());
// board.get(r).set(r, randomChar());
}
//prints out board in table form
for (ArrayList<Character> r : board) {
printRow(r);
}
System.out.println(board);
}
Run Code Online (Sandbox Code Playgroud)
您将多次向同一行添加相同的行.您必须添加唯一的行:
for (int c = 0; c < cSize; c++) {
board.add(new ArrayList<Character>());
}
Run Code Online (Sandbox Code Playgroud)