I'd like to ask you a question about the code for creating a java lottery number

Asked 1 years ago, Updated 1 years ago, 61 views

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

2022-09-21 15:26

1 Answers

    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.


2022-09-21 15:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.