我有一个文本文件名列表:MARY,PATRICIA,LINDA,BARBARA,ELIZABETH,JENNIFER,MARIA,我把它放入一个字符串数组。我希望能够搜索阵列,但我遇到了问题。我想使用快速排序算法对其进行排序,并使用二进制搜索进行搜索,但我正在尝试使用简单的方法。如果我搜索“MARY”,结果将是“MARY is not it”
public class NameSearch {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
FileReader woMen = new FileReader("names.txt");
String[] womenArray;
womenArray = new String[64];
BufferedReader reader = new BufferedReader(woMen);
String line = null;
for (int j=0;j<womenArray.length;j++)
{
womenArray[j] = reader.readLine();
}
reader.close();
int x = 0, y =0;
System.out.println("Name?");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
for(int i=0;i<womenArray.length;i++) {
if (input == womenArray[i]) {
System.out.println("Found! "+input);
}
System.out.println(womenArray[i]+" is not it");
}
}
}
答案 0 :(得分:1)
错误发生在if
声明中。要匹配字符串,请使用.equals
方法,如下所示:
System.out.println("Name?");
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
for(int i=0;i<womenArray.length;i++) {
if (womenArray[i].equals(input)) {
System.out.println("Found! "+input);
}
}
要对数组进行排序,请使用Array的排序方法:
Arrays.sort(womenArray);
Read about Arrays.sort(Object[] a) here
此外,您可以使用Arrays内置的binarySearch方法。详细了解here
在您的代码中,看起来像这样:
int location = Arrays.binarySearch(womenArray, input)
如果location
为负数,则表示找不到您要搜索的值。
int location = Arrays.binarySearch(womenArray, input.toUpperCase());
if (location > 0){
System.out.println("found it at " + location + " " + womenArray[location]);
}