Java.util.random - “绑定必须是正数”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26516302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:03:40  来源:igfitidea点击:

Java.util.random - "Bound must be positive"

javarandomindexoutofboundsexception

提问by Casper TL

I get this error:

我收到此错误:

java.lang.illegalException:
bound must be posotive

in the following line of code:

在以下代码行中:

Random random = new Random();
Item randomItem;
randomItem = new Item("NAME_HERE", "DESCRIPTION_HERE", 0000);
int randomNumber = random.nextInt(randomItem.randomNames.size());   *** ERROR HERE?!
randomItem.name = randomItem.randomNames.get(randomNumber);
addItem(randomItem);

This only happens the SECOND time i call the above method. It looks like (if i try print out the size of the randomNames arraylist, that it actually gets to 0. But it should not... Here is the randomItem, where the randomNames arraylist is created.. Nothing else but the above code has influence. ????

这仅在我调用上述方法的第二次发生。它看起来像(如果我尝试打印出 randomNames 数组列表的大小,它实际上会变为 0。但它不应该......这是 randomItem,在其中创建了 randomNames 数组列表......除了上面的代码没有别的影响。 ????

public ArrayList<String> randomNames;
randomNames.add("Key");
randomNames.add("Rock");
randomNames.add("Balloon");
randomNames.add("Boot");
randomNames.add("Knife");
randomNames.add("Pencil");

采纳答案by Maxaon3000

Your randomItems array size is 0. Check that

您的 randomItems 数组大小为 0。检查

  • randomNames is not declared static
  • The Item constructor fills the randomItems Array
  • randomNames 未声明为静态
  • Item 构造函数填充 randomItems 数组

回答by rickyalbert

Have you instantiated your list ?

你实例化了你的列表吗?

randomNames = new ArrayList<String>();

then you can add all the items you want.

然后你可以添加你想要的所有项目。