因此,我正在编写的某些代码中出现索引越界异常。我不明白的是,我知道我试图使用的索引元素存在。ArrayList和IndexOutOfBounds异常
下面的代码:
我有一个构造一个数组列表
public StixBoard(int number)
{
stixGame = new ArrayList<Integer>(number);
for (int i = 0; i < number; i++)
{
stixGame.add(i);
}
}
此块生成一个随机变量1-3
public int computeMove()
{
int numberOfStix = (int) (3.0 * Math.random()) + 1;
return numberOfStix;
}
真的直线前进,现在我在这里有一个方法需要提供参数并尝试从数组列表中删除这些数量的元素。如您所见,参数必须介于1和3之间,并且必须小于或等于数组列表的大小。否则,系统会提示用户输入另一个号码
public boolean takeStix(int number)
{
boolean logicVar = false;
placeHolder = stixGame.size();
if ((number >= 1 && number <= 3) && number <= placeHolder)
{
for (int i = 0; i < number; i++)
{
stixGame.remove(i);
logicVar = true;
}
} else if (number > 3 || number > placeHolder)
{
do
{
System.out
.println("Please enter a different number, less than or equal to three.");
Scanner numberScan = new Scanner(System.in);
number = numberScan.nextInt();
} while (number > 3 || number > placeHolder);
}
return logicVar;
}
因此,作为该程序运行时,computeMove()方法生成一个随机INT(假设电脑玩家的角色),并试图将该值转换为数字索引要从数组列表中删除。
这最终使我想到这一点:
How many stix on the table? 4
|||||||||| 4 stix on the table
It's the computer's turn!
The computer chose 3
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at StixBoard.takeStix(StixBoard.java:38)
at StixGame.main(StixGame.java:55)
因此,大家可以看到,数组列表的大小为4,但是在笔记本计算机掷出3,(这应该离开我1),我我留下了这个错误。我的数组列表如何从4号索引变成2号?
你“知道的事实”是不正确的,如果你得到这个异常;)使用调试器,一步一步通过你的代码。 –
哦,哦。我的其他语句是垃圾。 如果语句(数字> = 3)和(数字> placeHolder)到目前为止它似乎正在工作...我将最终打破else if语句来继续测试。不知道如何关闭主题 – UvrD
正确你是布赖恩,我以为我看到代码正常工作,但显然我不是 – UvrD