import java.util.*;
//lotto number
public class Pre4 {
public static void main(String[] args){
Random rann = new Random();
int[] a = new int[45];
int[] b = new int[7];
for(int q=0;q<a.length;q++){
a[q]=q+1;
}
for(int w=0;w<7;w++){
int r = rann.nextInt(45)+1;
b[w]=a[r];
}
System.out.print ("Results: ");
for(int t=0;t<b.length;t++){
System.out.print(b[t]+",");
}
}
}
I wrote a code to create a lottery number It runs well, but sometimes ArrayIndexOutOfBoundsException occurs What's the reason?
java random exception
for(int w=0;w<7;w++){
int r = rann.nextInt(45)+1;
b[w]=a[r];
}
The values that occur in intr=rann.nextInt(45)+1
in this part are 1 to 45
.
Therefore, when referring to array a[r]
, the variable r
can be 45, whereas array a
can only be referenced from 0 to 44
, which can cause errors.
© 2024 OneMinuteCode. All rights reserved.