Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Troubling generating a random order from an ArrayList

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);    
    }



}

}

like image 973
Qotsa42 Avatar asked Mar 09 '23 12:03

Qotsa42


1 Answers

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);
}
like image 60
weston Avatar answered Mar 29 '23 09:03

weston