【发布时间】:2015-10-02 20:25:14
【问题描述】:
我被指派创建一个程序,我必须在其中一种方法中提示用户输入他们想要删除其值的索引。我的问题是,当我尝试删除索引 0 时,我在索引 -1 处得到一个 ArrayIndexOutOfBoundsException。因此,为了解决这个问题,我尝试了i <= currentSize + 1,它修复了索引 0 的问题,但是最后一个索引出现了越界错误,因为 currentSize 比它们的数组大小大一。任何帮助,将不胜感激。
//This method drops the value of a selected index in the array.
private static void Drop ()
{
int m =0;
System.out.println("Choose an index that you would like to drop the value of:");
if(input.hasNextInt())
{
m = input.nextInt();
for(int pos = 0; pos < values.length; pos++)
{
if(pos == m)
{
for(int i = pos+1; i<=currentSize+1; i++)
{
values[i-1]= values[i];
values[i]=0;
}
currentSize--;
break;
}
else if(pos == 0)
{
System.out.println("ERROR: There is not an index at the specified location.");
}
}
}
else
{
System.out.println("ERROR: Please input a integer value.");
}
}
【问题讨论】:
-
从列表或数组中删除元素时,通常会向后遍历列表。这是因为如果列表自动调整大小(如 ArrayList),您不会跳过元素。
-
currentSize代表什么?我没有看到它在代码中的任何地方初始化。 -
缩进代码会更好
标签: java arrays indexoutofboundsexception