繁体   English   中英

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

[英]How Do i populate a 2d array with random values

我有一项任务,以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]);
        }
     }
 }
}

代码中的外观问题:

喜欢:

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");
}

您可以执行Math.round (Math.random() * 10) 我建议阅读Javadoc并了解random()方法的作用。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM