-1

我应该在字符串数组上编写顺序/线性搜索。我非常接近完成,但部分作业让我感到困惑。它表示将目标项与列表的连续元素进行比较,直到目标匹配或目标小于数组的当前元素。当没有数值时,字符串如何比另一个元素多或少?也许我只是没有正确地考虑它。到目前为止,这是我的程序:

public class SequentialSearchString {
public static boolean sequential (String[] numbers){
    //Set the target item to an arbitrary String that should return true.
    String T1 = "Frank";  

    for (int i = 0; i < numbers.length; i++){
        if (numbers[i] == T1){
            return true;    
        }
        if (numbers[i] != T1){
            numbers[i] = numbers[i+1];
        }           
    }
    return false;   
}

public static boolean sequential2 (String[] numbers){
    //Set the target key to String that should return false.
    String T2 = "Ian";
    for (int i = 0; i < numbers.length; i++){
        if (numbers[i] == T2){
            return true;    
        }
        if (numbers[i] != T2){
            numbers[i] = numbers[i+1];
        }
    }
    return false;   
}


public static void main(String[] args) {
    //Create a list of 8 Strings.
    String [] numbers = 
{"Ada", "Ben", "Carol", "Dave", "Ed", "Frank", "Gerri", "Helen", "Iggy", "Joan"};   
    //If the first target item (T1) is found, return Succuss. If not, return failure.
        if (sequential(numbers) == true){
            System.out.println("Success. 'T1' was found");
        }
        else {
            System.out.println("Failure. 'T1' was not found");  
        }
    //If the second target item (T2) is found, return Succuss. If not, return failure.
        if (sequential2(numbers) == true){
            System.out.println("Success. 'T2' was found");
        }
        else {
            System.out.println("Failure. 'T2' was not found");  
        }   
    }   
}

第一种方法工作正常,但我似乎在搜索不在列表中的元素时遇到问题。这是我运行程序后收到的错误消息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at SequentialSearchString.sequential2(SequentialSearchString.java:32)
at SequentialSearchString.main(SequentialSearchString.java:50)
Success. 'T1' was found

任何帮助理解分配和修复异常将不胜感激。

4

2 回答 2

1
numbers[i] = numbers[i+1];

很可能会导致您的ArrayIndexOutOfBoundsException.

您的条款检查i < numbers.length. 所以你设定了界限。但是,如果i == numbers.length - 1那时您将尝试访问i+1比您的数组更大的数组,那么它就超出了范围。

例如:numbers.length4。所以i可以 3。随着i+1您尝试访问numbers[4]哪一个将是第五个位置,因为数组开始0并且numbers[3]将是最后一个位置。

于 2012-02-15T22:50:06.260 回答
0

ArrayIndexOutOfBoundsException 是由于您使用的事实:

for (int i = 0; i < numbers.length; i++)

后者:

 numbers[i] = numbers[i+1];

当 i 等于 numbers.length-1(最后一次迭代)时,i+1 等于 numbers.length。然后您尝试读取错误的 numbers[numbers.length](有效索引从 0 到 numbers.length-1)。

你必须使用:

for(int i=0;i<numbers.length-1;i++) 

以防止异常。现在,我不确定它会解决你的整个问题,但肯定是例外。

于 2012-02-15T22:53:49.840 回答