java中如何将显式值随机分配给二维数组

java中如何将显式值随机分配给二维数组,java,multidimensional-array,Java,Multidimensional Array,我需要取集合{0,5,1,2,5}并用值随机填充一个nxm矩阵,我想我可以使用这段代码 public static void main(String[] args) { //create the grid final int rowWidth = 10; final int colHeight = 10; Random rand = new Random(); int [][] board = new int [rowWidth][colHeight]

我需要取集合{0,5,1,2,5}并用值随机填充一个nxm矩阵,我想我可以使用这段代码

public static void main(String[] args) {
    //create the grid
    final int rowWidth = 10;
    final int colHeight = 10;

    Random rand = new Random();

    int [][] board = new int [rowWidth][colHeight];

        //fill the grid
        for (int[] board1 : board) {
            for (int col = 0; col < board1.length; col++) {
                board1[col] = rand.nextInt(5);
            }
        }

        //display output
        for (int[] board1 : board) {
            for (int j = 0; j < board1.length; j++) {
                System.out.print(board1[j] + " ");
            }
            System.out.println();
publicstaticvoidmain(字符串[]args){
//创建网格
最终整数行宽=10;
最终高度=10;
Random rand=新的Random();
int[]board=新int[rowWidth][colHeight];
//填写表格
对于(int[]板1:板){
for(int col=0;col

然后将每个数字{0,1,2,3,4}映射到{0,5,1,2,5},然后重新绘制矩阵……有更好的方法吗……如何从一开始就用指定的数字随机填充矩阵?

您可以保留一个数组,其中包含可能的值,然后从该数组中随机选择一个:

final int rowWidth = 10;
final int colHeight = 10;
final double[] possibleValues = {0.0, 0.5, 1.0, 2.0 ,5.0};

Random rand = new Random();

double[][] board = new double[rowWidth][colHeight];

for (double[] board1 : board) {
    for (int col = 0; col < board1.length; col++) {
        board1[col] = possibleValues[rand.nextInt(possibleValues.length)];
    }
}
final int rowWidth=10;
最终高度=10;
最终双[]可能值={0.0,0.5,1.0,2.0,5.0};
Random rand=新的Random();
double[]board=新的double[rowWidth][colHeight];
对于(双[]板1:板){
for(int col=0;col