我正在尝试随机分配数字。我知道Math.random()
只在0和1之间,并试图将其乘以10,但它仍然没有显示任何随机数:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
代码:
public static void main(String[] args) {
int[][] mdArray = new int[5][5];
for(int i = 0; i<mdArray.length; i++){
for(int j = 0; j<mdArray[i].length; j++) {
mdArray[i][j] = (int)Math.random()*10;
System.out.print(mdArray[i][j] + " ");
}
System.out.println("");
}
}
发生这种情况是因为您的强制转换错误。强制转换仅适用于小于1的Math.random()
,因此它始终强制转换为0和0*x = 0
。
你必须写(int) (Math.random() * 10)
而不是(int)Math.random()*10
。