2011-12-21 35 views
-1

在下面的程序中,我有19個元素在數組ID。由於我使用隨機類,它隨機從數組中重複檢索id。我需要避免重複值並隨機打印數組中的所有值。Java隨機類程序

import java.util.Random; 
public class random { 
public static void main(String[] args) { 
    int[] id={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}; 
    Random rand=new Random(); 
    for(int i=0;i<20;i++) 
    { 
      int alength=id.length; 
    //System.out.println("Length="+alength); 
    int index1=rand.nextInt(alength); 
    int team=id[index1]; 
    System.out.println("Team="+team); 
    }}} 
+1

我想先洗牌的陣列,然後只是迭代它,並打印值... – home 2011-12-21 08:43:52

+1

這是功課嗎? – Ishtar 2011-12-21 08:45:17

回答

4

您可以隨機數組的元素,然後打印出來

Collections.shuffle(Arrays.asList(array)); 
0

你必須記住所有以前的數字知道,如果電流是duplicate.So這將是更好地構建一個新的字符串,不首先複製,然後隨機打印數字。

+1

在洗牌列表之前使用Set更容易。然後刪除重複項。 – proko 2011-12-21 08:56:24