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