Alarm generating random order from ArrayList

general newbie here. I wrote a program in java to help randomize the order of groups for the concert that I am organizing. I have problems with the code. The output that I get ends after printing three lines instead of four, often repeats lines (which I do not want) and ends after the third line with the following error:

"java.lang.IllegalArgumentException: the border 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);    
    }



}

}

+4
source share
3 answers

You get the exception thrown in the last loop when you call nextInt(0):

"main" java.lang.IllegalArgumentException:          java.util.Random.nextInt(Random.java:388)

:

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
}

remove get , remove :

System.out.println(bands.remove(index));

, Collections.shuffle:

Collections.shuffle(bands);
for (String band : bands) {
    System.out.println(band);
}
+3

Collection.shuffle(). JDK , , .

, .

Random.nextInt(x) , 0 x - 1. i 4 1:

for (int i = 4; i >= 1; i--)

for . , , , . , , i, index. :

bands.remove(index);

4 2 . , .

+2

Try the code below. It works for your problem.

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");
    int i=1;
    Collections.shuffle(bands);
    for(String band: bands){

        System.out.println(i++ + ". " +band);
    }

}

The reason you get the exception: the value of the nextInt argument must be greater than zero.

public int nextInt(int n) {
   if (n <= 0)
     throw new IllegalArgumentException("n must be positive");

   if ((n & -n) == n)  // i.e., n is a power of 2
     return (int)((n * (long)next(31)) >> 31);

   int bits, val;
   do {
       bits = next(31);
       val = bits % n;
   } while (bits - val + (n-1) < 0);
   return val;
 }
+2
source

Source: https://habr.com/ru/post/1673047/


All Articles