我有一个任务,用 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/