本文介绍了非法参数异常:n必须为正的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主类:

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);
}

应用()方法:

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();
    }

收到此错误:

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)

想不通这是什么意思,什么n为重的presentative?

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

推荐答案

在此行

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

您正试图生成随机数。

不过你有空usedArray,所以返回0。你不能在0范围内产生随机数为0 EXLUSIVE,所以它抛出异常。该值必须是1或更高。

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.

请注意文件:值介于0(含)和指定值(不),因此,例如所有呼叫generator.nextInt(1)返回0, generator.nextInt(2)返回0或1 ...

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

这篇关于非法参数异常:n必须为正的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 13:01