java - 列表已满时抛出IllegalArgumentException

标签 java arraylist error-handling illegalargumentexception throw

由于某些原因,我在这些特定的行上不断出错。列表中确实有索引,但是由于某些奇怪的原因,当我尝试运行它时,它给了我这个错误。

这是它抛出的错误并说了几行。

Exception in thread "main" java.lang.IllegalArgumentException: bound must be 
positive
at java.util.Random.nextInt(Unknown Source)
at Room.getRandomEnemy(Room.java:95)
at Room.<init>(Room.java:32)
at Game.startGame(Game.java:102)
at Main.main(Main.java:9)

这是我的代码。
static ArrayList<String> enemys = new ArrayList<>(Arrays.asList("Red minion", "Blue Minion", "Purple Minion", "Blitz", "Katarina", "Green Minion")); 
private String contents; 
static ArrayList<String> items = new ArrayList<>(Arrays.asList("Mana Potion", "Health Potion", "Pickaxe", "Cloth-Armor", "Cull"));

int randomIndex = rand.nextInt(enemys.size());
this.getRandomEnemy(enemys);
Room inhibitor1 = new Room("inhibitor1", inhibitor1Desc, inhibi1Exit, 
console);
game.startGame();

最佳答案

@Lashane是对的!

enter image description here

如果您的敌人列表为空,它将返回0,因此Random.nextInt()将抛出IllegalArgumentException。

关于java - 列表已满时抛出IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43400111/

相关文章:

java - java中构造函数类型不匹配

Java - 从ArrayList中分离并显示元素,如带有子列表的列表

c# - 如何访问列表内的类内的变量?

swift - 意外地发现 nil 解包了一个可选的 - 为什么我会收到 fatal error ?

python - python中的 “unpacking” nltk错误

php - PHP中没有错误信息

java - 使用 Apache POI 从 Java 将 mysql 数据导出到 excel

java - 带数字键的枚举

java - 如何获取当前 bean 名称/id 以在 bean 初始化中使用它来构建占位符名称

Java 游戏 - 如何使用 Arraylist 添加敌人?