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

标签 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]);
        }
     }
 }
}

最佳答案

代码中的外观问题:

喜欢:

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

关于java - 如何用随机值填充二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36753874/

相关文章:

C++ 二维数组

java - 有没有一种方法可以让别人在看不到代码的情况下运行我的 Java 程序?

c++ - 智能感知 : an array may not have elements of this type

java - 使用 AND/OR 组合的 Elasticsearch Java 查询

matrix - APL:数组的元素替换和乘法

c# - 如何在 C# 中生成 0 到 1 之间的随机数?

random - swift 随机数

c++ - 生成随机字母数组并计算出现次数

java - 获取用于执行 Web 应用程序的类路径条目

java - 检查对象的类是否为日期的条件