如何使用随机值填充二维数组

时间:2016-04-20 19:53:39

标签: java multidimensional-array random

我有一个赋值,用0到9之间的随机数填充数组。然后以矩形格式打印出来。我已经在尝试将随机整数放入数组中时遇到了麻烦。请指出我正确的方向

import java.util.*;
public class ThreebyFour
{
    public static void main (String[] args)
    {
     int values[][] = new int[3][4];
     for (int i = 0; i < values.length; i++) 
     {
        for (int j = 0; j < values.length; j++) 
        {
          values[i][j] = ((int)Math.random());
         System.out.println(values[i][j]);
        }
     }
 }
}

2 个答案:

答案 0 :(得分:2)

代码中的装饰性问题:

喜欢:

values[i][j] = ((int)Math.random());

这会将所有元素分配为零,因为随机值的返回介于0和1之间[0,1],并且转换为整数将返回零。

和此:

for (int j = 0; j < values.length; j++) 

第二个for循环会更好,如果你这样做计算该行的元素...就像我在评论中写的那样......

即做:

for (int j = 0; j < values[i].length; j++) {

修正代码:

public static void main(String[] args) {
    int values[][] = new int[3][4];
    for (int i = 0; i < values.length; i++) {
        // do the for in the row according to the column size
        for (int j = 0; j < values[i].length; j++) {
            // multiple the random by 10 and then cast to in
            values[i][j] = ((int) (Math.random() * 10));
            System.out.print(values[i][j]);
        }
        // add a new line
        System.out.println();
    }
    System.out.println("Done");
}

答案 1 :(得分:0)

你可以做Math.round (Math.random() * 10)。我建议阅读javadoc并理解random()方法的作用。

https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()

相关问题