Illegal argument exception: n must be positive

后端 未结 3 1993
南方客
南方客 2020-12-21 17:27

main class:

public class ECONAPP2 {
static Scanner input= new Scanner(System.in);
static int score = 0;
static ArrayList used         


        
相关标签:
3条回答
  • 2020-12-21 17:56

    n represents the parameter of the Random#nextInt(int n) method. The parameter must be a positive integer. In your example, the size of the array could be 0, thus resulting in the exception.

    0 讨论(0)
  • 2020-12-21 18:01

    In this line

    int randomNumber = generator.nextInt(usedArray.size());
    

    you are trying to generate random number.

    However you have empty usedArray, so it returns 0. You cant generate random number in range 0 to 0 exlusive, so it throws exception. The value must be 1 or higher.

    Note documentation : "value between 0 (inclusive) and the specified value (exclusive)", so for example generator.nextInt(1) return 0 on all calls, generator.nextInt(2) returns 0 or 1...

    0 讨论(0)
  • 2020-12-21 18:14

    You want to change the order you're calling methods in you main method. Try this:

    public static void main(String[] args){
        arrayContents();
        app();
    }
    

    This way when you call app(), your ArrayList has items in it.

    0 讨论(0)
提交回复
热议问题