我应该在String数组上编写顺序/线性搜索。我非常接近完成,但部分任务让我感到困惑。它表示将目标项与列表的连续元素进行比较,直到目标匹配或目标小于比数组的当前元素为止。当没有数值时,String如何比其他元素更多或更少?也许我只是没有正确地思考它。到目前为止,这是我的计划:
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
非常感谢任何理解分配和修复异常的帮助。
答案 0 :(得分:1)
numbers[i] = numbers[i+1];
可能会导致您的ArrayIndexOutOfBoundsException
。
您的条款检查i < numbers.length
。所以你设置了界限。但是,如果i == numbers.length - 1
,那么您将尝试访问比您的数组更大的i+1
,因此它超出范围。
例如:numbers.length
为4
。所以i
可以
3
。使用i+1
,您尝试访问numbers[4]
,这将是第五个位置,因为数组以0
开头,而numbers[3]
将是最后一个位置。
答案 1 :(得分:0)
ArrayIndexOutOfBoundsException是由于您使用的事实:
for (int i = 0; i < numbers.length; i++)
和后者:
numbers[i] = numbers[i+1];
当i等于numbers.length-1(最后一次迭代)时,i + 1等于numbers.length。然后你尝试读取错误的数字[numbers.length](有效索引从0到numbers.length-1)。
你必须使用:
for(int i=0;i<numbers.length-1;i++)
防止异常。现在,我不确定它会解决你的整个问题,但肯定是例外。