Java IllegalArgumentException:绑定必须为正

Java IllegalArgumentException:绑定必须为正,java,Java,下面是我的代码部分,它引发异常: List<Car> car1store = new ArrayList<>(); //adding any number of cars to car1store Random rnd = new Random(); double randNumber = rnd.nextDouble(); if (randNumber < 0.25) { int attempt = rnd.nextInt(car1store.siz

下面是我的代码部分,它引发异常:

List<Car> car1store = new ArrayList<>();

//adding any number of cars to car1store

Random rnd = new Random();
double randNumber = rnd.nextDouble();

if (randNumber < 0.25) {
    int attempt = rnd.nextInt(car1store.size()); 
    Car car = car1store.get(attempt);
}
List car1store=new ArrayList();
//向car1store添加任意数量的汽车
随机rnd=新随机();
double randNumber=rnd.nextDouble();
如果(随机数<0.25){
int trunt=rnd.nextInt(car1store.size());
Car Car=car1store.get(尝试);
}
我已经搜索过为什么会出现这个异常,但我真的找不到car1store.size()怎么可能是负数。它可以是的最小值只能是零。你能看出我的错误吗

边界必须是正的

错误消息在这里清楚地说明了问题。
ArrayList
的大小为
0
。这不是积极的

这里更大的问题是,您试图从空列表中
.get()

您应该向列表中添加一些元素,然后尝试访问它

边界必须是正的

错误消息在这里清楚地说明了问题。
ArrayList
的大小为
0
。这不是积极的

这里更大的问题是,您试图从空列表中
.get()


您应该向列表中添加一些元素,然后尝试访问它。

您遇到了这个问题,因为
car1store.size()
0
,而
rnd.nextInt
需要大于
0
的边界。您可以理解以下代码的问题:

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        Random rand = new Random();
        System.out.println(rand.nextInt(0));
    }
}
输出:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
    at java.base/java.util.Random.nextInt(Random.java:388)
    at Main.main(Main.java:6)

您遇到此问题是因为
car1store.size()
0
并且
rnd.nextInt
需要大于
0
的边界。您可以理解以下代码的问题:

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        Random rand = new Random();
        System.out.println(rand.nextInt(0));
    }
}
输出:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
    at java.base/java.util.Random.nextInt(Random.java:388)
    at Main.main(Main.java:6)

首先,我会让car1store成为一个数组列表,而不是依赖多态性。更改后,请发送发生错误的准确行,好吗?谢谢零不是正的。这也不是消极的,但不是积极的。
nextInt()
的参数是一个排他性上限,因此它必须大于0-毕竟,要求“a number>=0,但也<0”是没有意义的@PatrickOshea yes,刚刚再次出现。做了几次尝试,它又出现了。
int-trunt
也可能是负数,因为
rnd
。请参阅此行:int trunt=rnd.nextInt(car1store.size());首先,我会让car1store成为一个数组列表,而不是依赖多态性。更改后,请发送发生错误的准确行,好吗?谢谢零不是正的。这也不是消极的,但不是积极的。
nextInt()
的参数是一个排他性上限,因此它必须大于0-毕竟,要求“a number>=0,但也<0”是没有意义的@PatrickOshea yes,刚刚再次出现。做了几次尝试,它又出现了。
int-trunt
也可能是负数,因为
rnd
。请参阅此行:int trunt=rnd.nextInt(car1store.size());他的代码注释说他在添加汽车。这不是他的问题。@neildo他只注释了,没有在列表中添加任何元素。他的代码注释说他在添加汽车。这不是他的问题。@neildo他只注释了,没有在列表中添加任何元素。