2014-06-13 59 views
0

我必須填充多維數組的1行,整數從1到3完全隨機。 例如:如果我將打印該行它可能給予:1 2 2 1 2 3 1 2 3如何填充具有特定隨機數的數組(java)

我們做到這一點,我想下面的代碼將工作:

private void fillArray() 
    { 
     for(int i=0; i<10;i++) 
     { 
     PincodeRandom[0][i]=i; 
     PincodeRandom[1][i]= (int)Math.random()*3 +1; 
     } 
    } 

然而這導致成只用1(隨機)整數填充整個第二行。 我該如何解決這個問題?

+0

強制性[XKCD(http://www.xkcd.com/221/) – clcto

+0

你是對我搞砸了簡單的數學... 的結果整天編程 – user3401578

回答

0

(int)將通過3投Math.random() 0您之前乘法,從而導致。在0 * 3 + 1這始終是1.嘗試:

(int)(Math.random()*3) + 1; 
-1

這是因爲(INT)的Math.random()導致它等於0,因爲的Math.random()是一個雙其間總是0和1。

相反,導入了java.util.Random類。

而且使用它像: 新的隨機()nextInt(2)+1

+1

但是不要這樣做,因爲種子一般是根據系統時間計算的,而且這種情況處於嚴密的循環中。 – clcto

+0

或者至少在應用'(int)'之前在'Math.random()* 3'中放置一些參數。 –

+0

這個作品!非常感謝你! – user3401578

0

嘗試......

Random r = new Random(); 
for(loop){ 
    PincodeRandom[1][i]= = r.nextInt(4 - 1) + 1; 
} 
1

如果你要使用Random類,讓河畔e你創建了一個環以外的實例,因爲new Random()使用系統時間作爲種子。因此,如果在同一個勾號中創建兩個隨機數,它們將產生相同的隨機數字序列。

private void fillArray() 
{ 
    Random rand = new Random(); 
    for(int i=0; i<10;i++) 
    { 
    PincodeRandom[0][i]=i; 
    PincodeRandom[1][i]= rand.nextInt(2) + 1; 
    } 
} 
0

試試這個:

import java.util.Random; 


public class Test { 
public static void main(String[] args){ 
    int[][] array = new int[2][10]; 
    Random rand = new Random(); 
    for(int i=0; i<10;i++) 
    { 
    array[0][i]=i; 
    array[1][i]= (int)rand.nextInt(3) +1; 
    } 
    for (int j=0;j<10;j++){ 
    System.out.println(Integer.toString(array[1][j])); 
    } 
} 
}