2013-03-16 106 views
0

我有這個班,它對我來說工作得很好。它給5位數的隨機數。我無法實現的是5個數字彼此不同,我的意思是在5位數字中不重複它的數字。如果您約束這樣的結果隨機5個不同的數字

import java.util.Random; 

public class Test 
{ 

    public int[] dedo() 
    { 
     Random diceRoller = new Random(); 
     int[] cifra = new int[5]; 
     for (int i = 0; i < cifra.length; i++) 
     { 
      int roll = diceRoller.nextInt(9); 
      cifra[i] = roll; 
      System.out.print(roll); 
     } 
     return cifra; 
    } 
} 

回答

1

它不是一個真正隨機的,而是一個快速討厭的方式做,這將與Collections.shuffle()

List<Integer> digits = Arrays.asList(0,1,2,3,4,5,6,7,8,9); 
Collections.shuffle(digits); 
return digits.subList(0, 4).toArray(); 
+0

謝謝你的男人。但就像你說的那樣,它不是隨機的。 – 2013-03-17 01:55:19