total newbie here. I've written a program in java to help randomize the order of bands for a concert I'm organizing. I'm having trouble getting the code to work. The output I get terminates after printing three strings instead of four, often repeats strings (which I don't want) and terminates after the third string with the following error:
"java.lang.IllegalArgumentException: bound must be positive"
Can anyone help troubleshoot my code?
public class BandRandomizer
{
public static void main(String[] args)
{
ArrayList<String> bands = new ArrayList<>();
bands.add("Band A");
bands.add("Band B");
bands.add("Band C");
bands.add("Band D");
Random gen = new Random();
int index = 0;
for (int i = 3; i >= 0; i--)
{
index = gen.nextInt(i);
System.out.println(bands.get(index));
bands.remove(i);
}
}
}
You're getting an exception thrown in the last loop as you are calling nextInt(0)
:
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive at java.util.Random.nextInt(Random.java:388)
Should be:
for (int i = 4; i > 0; i--) { //changed
index = gen.nextInt(i); // return value in range [0..i) perfect for indexing
System.out.println(bands.get(index));
bands.remove(index); //changed
}
You can also remove
and get
in one fell swoop as remove
returns the removed item:
System.out.println(bands.remove(index));
But this is a bad way of shuffling, use Collections.shuffle
:
Collections.shuffle(bands);
for (String band : bands) {
System.out.println(band);
}
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