如何从2D数组中随机选择一个元素,并用char' M'填充该元素?
答案 0 :(得分:1)
你在找这样的东西吗?
// Your array of Char with the length of 5 by 5
char[][] arrayOfChar = new char[5][5];
// Generating a radom number with min being 0 and max being length - 1
Random rand = new Random();
int x = rand.nextInt(arrayOfChar[0].length);
int y = rand.nextInt(arrayOfChar[1].length);
// Random position in array assigned M
arrayOfChar[x][y] = 'M' ;
如果您想要int
数组
// Your array of int with the length of 5 by 5
int[][] arrayOfInt = new int[5][5];
// Generating a radom number with min being 0 and max being length - 1
Random rand = new Random();
int x = rand.nextInt(arrayOfInt[0].length);
int y = rand.nextInt(arrayOfInt[1].length);
// Random position in array assigned number 8
arrayOfInt[x][y] = 8 ;
答案 1 :(得分:-2)
也许是这样的?
public class random2DChar {
public static void main(String args[]) {
char[][] char2DArr = new char[10][10];
Random random = new Random();
int x = random.nextInt(char2DArr.length);
char2DArr[x][x] = 'M';
System.out.println(Arrays.deepToString(char2DArr));
}
}