非法参数异常:n 必须为正 [英] Illegal argument exception: n must be positive

查看:26
本文介绍了非法参数异常: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);
}

app() 方法:

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 代表什么?

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

推荐答案

在这一行

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

您正在尝试生成随机数.

you are trying to generate random number.

但是你有空的usedArray,所以它返回0.你不能生成0到0范围内的随机数,所以它会抛出异常.该值必须为 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 必须为正的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆