尝试按照我们给出的一些伪代码用Java编写线性搜索算法。 (很抱歉,这是一个愚蠢的问题)
我对Java还是很陌生,可能有一种更简单的方法来执行此操作,但是我不确定,因为伪代码似乎无法正常工作。我试着摆弄数字-可以快速解决吗?
我已经使用了以下代码,但始终获取'java.lang.ArrayIndexOutOfBoundsException'
// Linear Search Standard Algorithm
private static void linearSearch() {
// Declare a new scanner object
Scanner in = new Scanner(System.in);
// Declare variables used in the program
String[] arr = new String[] {"Mick", "Jerry", "Bob", "Chris"};
String name = "";
boolean found = false;
int position = -1;
int counter = -1;
// Prompt User to enter a value to be searched for
System.out.print("Search For: ");
name = in.nextLine();
// Search for the requested item
while (found == false || counter < arr.length) {
counter += 1;
if (name == arr[counter]) {
found = true;
position = counter;
}
}
// Output whether the variable was found or not
if (found == true) {
System.out.println(name + " was found at position " + position + " of the array.");
} else {
System.out.println(name + " could not be found in the array.");
}
}