im trying to select randomly from an array to print it, then remove it from the array, to avoid printing out the same number twice. i am a bit of a java novice so was wondering if someone could point me where im going wrong.
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)]);
}
thanks
Random doesn't give gurranty of unique number. you can do following instead.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With