2014-04-04 114 views
4

即时尝试从数组中随机选择以便将其打印出来,然后将其从数组中删除,以避免打印出两次相同的数字。我是一个java新手,所以想知道如果有人可以指出我哪里会出错。如何从int数组中随机选择,然后删除选中的元素

public static void main(String[] args) { 
    int[] colm = { 1, 2, 3, 4, 5, 67, 87 }; 
    Random rand = new Random(); 

    for (int i = 0; i < 5; i++) 
     System.out.println(" " + colm[rand.nextInt(colm.length)]); 

} 

感谢

+0

你不想打印相同数量的两倍,因此,每次你将不得不减少随机数的范围内创建 – Kraken

+0

此外,你是不是从Array删除数字你选择了后。你只是在控制台上打印它。 – Kraken

+0

由于我们不住洞穴,我们不穿人体皮肤,请不要使用阵列。欢呼声 – Kraken

回答

5

随机不给唯一编号的保证。您可以改为执行以下操作。

public static void main(String[] args) { 
    int[] colm = { 1, 2, 3, 4, 5, 67, 87 }; 
    List l = new ArrayList(); 
    for(int i: colm) 
     l.add(i); 

    Collections.shuffle(l); 

    for (int i = 0; i < 5; i++) 
     System.out.println(l.get(i)); 

} 
+1

比别人更优雅,但你没有删除元素。我对吗? – Gabrer

+1

@Gabrer。是的,我没有删除。因为虽然标题要求从数组中删除,但OP的主要目标是避免打印重复条目。 – stinepike

+1

好的!我明白。 但实际上,我在Google上选择了这个答案,因为标题中有“删除”。 改善答案取决于你(无论如何,它只需要调用“remove()”方法)。 – Gabrer

0

您更好地使用set或map来保存数据,然后创建属于中集/图的长度随机数,并与(随机)索引中删除。

+1

Set和Map没有索引。列表会更合适。 –

+0

另外也许OP是为了锻炼而做的,所以能够给他一个答案代码是很好的。 –

3

您错过的删除部分。尝试这样的:

public static void main(String[] args) 
{ 
    Integer [] colm = {1,2,3,4,5,67,87}; 
    final List<Integer> ints = new ArrayList<Integer>(Arrays.asList(colm)); 
    Random rand = new Random(); 

    for(int i = 0; (i<5) && (ints.size() > 0); i ++) { 
     final int randomIndex = rand.nextInt(ints.size()); 
     System.out.println(" " + ints.get(randomIndex)); 
     ints.remove(randomIndex); 
    } 
} 
+0

如果你使用list作为final,它会抛出异常。 – Arjit

+0

异常不是由于final,Arrays.asList(colm)创建了不支持删除的固定大小的List,修正了:) – enterbios

+0

是的你是对的....感谢让我知道真正的原因... – Arjit

相关问题