2016-04-20 100 views
1

我有一個任務,用0-9範圍內的隨機數填充數組。然後以矩形格式打印出來。我在嘗試將隨機整數放入數組中時遇到了問題。請指向正確的方向我如何用隨機值填充2d數組

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]); 
     } 
    } 
} 
} 
+0

它打印出全零 –

+0

當然如此。 Math.random()返回什麼?並且當你將它轉換爲int時? – stdunbar

+0

如何使其打印0-9(含)。對不起,我是非常新的Java和編碼一般 –

回答

1

在你的代碼化妝品的問題:

,如:

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