我创建了一个二维数组,希望用10以内的随机数字填充。但是,打印出来的最终结果都是零。我看不出我的代码有什么问题,我确信一切都是正确的。我在Stack Overflow上搜索了类似的问题,但找不到与我类似的问题。我的代码如下:
int [][] array = new int [3][3];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++)
{ array[i][j] = ( (int) Math.random() * 10 );
System.out.print(array[i][j] + " "); }
System.out.println(" "); }
问题很简单。这只是您将Math.random()
强制转换为int,而不是乘法运算的结果
你的原始代码是这样的:
array[i][j] = ( (int) Math.random() * 10 );
它将Math.random()
强制转换为int
,而Math.random()
在[0..1]间隔中返回双。强制转换为int
的结果将为0。
您应该做的是强制转换Math.random()
与10:的乘积
array[i][j] = ( (int) (Math.random() * 10) );
以下是完整的工作代码:
public class RandomArray{
public static void main(String []args){
int [][] array = new int [3][3];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++){
array[i][j] = ( (int) (Math.random() * 10) );
System.out.print(array[i][j] + " ");
}
System.out.println(" ");
}
}
}