2014-12-01 93 views
1

我需要用整數填充一個向量,但我有一些麻煩,我需要用隨機數填充它,但不是連續兩個數字。 (當然不是這樣:1,4,4,3,5,9) 我做了這個代碼,但它不能很好地工作:Android,隨機連續兩次不重複相同的數字

  • @首次洛哈= 1;
  • 但直到比賽:loja ++;
  • int [] con;

隨機法:

private int nasiqim (int max){ 
Random nasiqimi = new Random(); 
int i = 0; 
i=nasiqimi.nextInt(max); 
return i; 
} 

工作代碼:

int i; 
    con = new int [loja]; 
    for (i=0; i<loja; i++) 
    { 
     con[i] = nasiqim(8); 
     if(i>0){ 
     while(con[i]==con[i-1]) 
     { 
     con[i] =nasiqim(8); 
     } 
     } 
     i++; 
    } 

的結果是這樣的:

  1. 1,4
  2. 1,4,1
  3. 1,4,1,4
  4. 1,4,1,4,1
  5. 5,3,5,3,5,3
  6. 5,3,5 ,3,5,3,5

而且這不是我需要,我需要的數字,真正隨機的,不是這樣的, 將是巨大的,如果名單將是這樣的:1,5, 6,7,3,0,2,4,1,0,2,3 ...

謝謝!

+1

您的隨機生成器位於方法內部,將其作爲類的靜態成員提取。 – enrique7mc 2014-12-01 21:17:00

+0

我也試過,是一樣的:( 或你的意思是隨機的聲明在外面? – 2014-12-01 21:21:13

+1

@chais可能是正確的,作爲一個靜態成員它可以解決問題。因爲目前,每當你調用'nasiqim ',它會創建一個新的Object for Random(),所以它會忘記以前的值,哪些會導致重複。 – 2014-12-01 21:25:04

回答

1
private int[]   con   = null; 

private final Random nasiqimi = new Random(); 

/** 
* Test run random. 
*/ 
@Test 
public void testRunRandom() { 
    int loja = 10; 
    con = new int[loja]; 
    for (int i = 0; i < loja; i++) { 
     int nextRandom = 0; 
     while (true) { 
      nextRandom = nasiqim(8); 
      if (i == 0 || con[i - 1] != nextRandom) { 
       con[i] = nextRandom; 
       break; 
      } 
     } 
    } 

} 

/** 
* Gets the random. 
* 
* @param max the max 
* @return the random 
*/ 
private int nasiqim(int max) { 
    return nasiqimi.nextInt(max); 
} 
+0

謝謝我只是複製了這段代碼,現在我得到了我想要的一切! 也沒有重複:D – 2014-12-01 22:10:30

1

我創建了一個示例類

import java.util.*; 

public class Foo { 

    static Random r = new Random(); 
    static int[] con; 
    static int loja = 8; 

    private static int randomInt(int max) { 
     return r.nextInt(max); 
    } 

    public static void main(String args[]) { 
     int i; 
     con = new int[loja]; 
     for (i = 0; i < loja; i++) { 
      con[i] = randomInt(8); 
      if (i > 0) { 
       while (con[i] == con[i - 1]) { 
        con[i] = randomInt(8); 
       } 
      } 
     } 

     System.out.println(Arrays.toString(con)); 
    } 
} 

所有變量都是靜態的,發現我擺脫我的++;在for循環結束時增加。

+0

謝謝,你真的幫了我!:) – 2014-12-01 21:59:29

相關問題