gpt4 book ai didi

java - ArrayList 和 IndexOutOfBounds 异常

转载 作者:行者123 更新时间:2023-12-01 07:11:19 25 4
gpt4 key购买 nike

因此,我在编写的某些代码中遇到了索引越界异常。我不明白的是,我知道我正在尝试使用的索引元素存在。

代码如下:

我有一个数组列表的构造函数

    public StixBoard(int number)
{
stixGame = new ArrayList<Integer>(number);

for (int i = 0; i < number; i++)
{
stixGame.add(i);
}

}

该 block 生成一个随机变量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?

最佳答案

您从头到尾迭代列表,并在每一步删除一个元素。这使得列表中的所有元素都向左移动。

第一次迭代:i = 0

[1, 2, 3]

第二次迭代:i = 1

[2, 3]

第三次迭代:i = 2

[2] -> IndexOutOfBoudsException. There is no index 2 in this list.

而是从末尾迭代到开头。这将使其正确且更快,因为列表不必从右到左复制所有元素。

关于java - ArrayList 和 IndexOutOfBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13771128/

25 4 0