Illegal argument exception: n must be positive

时间秒杀一切 提交于 2019-12-31 03:26:10

问题


main class:

public class ECONAPP2 {
static Scanner input= new Scanner(System.in);
static int score = 0;
static ArrayList<Integer> usedArray = new ArrayList<Integer>();

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

public static void arrayContents() { 
    usedArray.add(2);
    usedArray.add(1);
}

app() method:

public static void app() {
    Random generator = new Random ();
    int randomNumber = generator.nextInt(usedArray.size());
    System.out.println(randomNumber);
    if (randomNumber == 2) {
        score();
        question2();
        usedArray.remove(2);
        app();
    }
    if (randomNumber == 1) {
        score();
        question1();                
        usedArray.remove(1);
        app();
    }

getting this error:

Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Random.java:250)
at ECONAPP2.app(ECONAPP2.java:65)
at ECONAPP2.main(ECONAPP2.java:10)

can't work out what this means and what n is representative of ?


回答1:


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...




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/19304463/illegal-argument-exception-n-must-be-positive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!