Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

java - Illegal argument exception: n must be positive

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...