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); } }
}
You get the exception thrown in the last loop when you call nextInt(0):
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 :
remove
get
System.out.println(bands.remove(index));
, Collections.shuffle:
Collections.shuffle
Collections.shuffle(bands); for (String band : bands) { System.out.println(band); }
Collection.shuffle(). JDK , , .
Collection.shuffle()
, .
Random.nextInt(x) , 0 x - 1. i 4 1:
Random.nextInt(x)
i
for (int i = 4; i >= 1; i--)
for . , , , . , , i, index. :
index
bands.remove(index);
4 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; }
Source: https://habr.com/ru/post/1673047/More articles:Отмена Предупреждение: 0,18.1 при импорте GridSearchCV - pythonPython Pandas using previous value in Dataframe - pythonNVIDIA-SMI failed because it could not contact the NVIDIA driver - gpuConditional formatting based on cell above - excelWorking hours of Android Studio / IntelliJ IDEA - androidGlobal types in typescript - typescriptHow to upgrade Intellij to 2017 on Linux? - intellij-ideaInserting a dictionary into a bunch - pythoncorrectly adding defer attribute to script tag with pure javascript - javascriptКак сделать Flexbox (flex-grow) учитывать контент для определения размера? - htmlAll Articles