在我的程序中,我首先搜索一个值,如果它存在,给出数组位置,如果没有给出-1,但当我试图在程序中返回错误消息时,输入的值找不到,因此没有删除,我收到了一个实际的错误。这听起来可能令人困惑,如果您看不到我的代码,我可以尝试解释更多。有人能帮帮忙吗?
private int search(int s){
    int position = 0;
    while(nums[position] != s){
        if(position < size)
            position++;
        else
            position = -1;
    }
    return position;
}
public void delete(int d){
    int value = search(d);
    if(search(d) == -1){
        System.out.println("The value " + d + " was not found and cannot be deleted");
    }
    else
    for(int n = size; n > value; n--)
        nums[value] = nums[size];
}我收到错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Numbers.search(Numbers.java:44)
at Numbers.delete(Numbers.java:53)
at Assignment7.main(Assignment7.java:31)发布于 2014-04-18 13:49:03
我不懂Java,但我了解C#。我认为搜索方法会搜索现有的条目。
不要使用if条件。
在搜索代码和Catch块中捕获异常,执行以下操作:
System.out.println("The value " + d + " was not found and cannot be deleted");https://stackoverflow.com/questions/23148154
复制相似问题