我有一个为此java程序导入的名称和性别的txt文件。扫描仪应该接受用户输入(名称和性别)并逐行比较以在文本文件中找到它,然后打印找到名称的行。但是,只有一些名称有效,而有些名称无效。我想这可能是因为程序只读取所有其他行,但我不确定是否是问题,或者如何修复它。 链接到名称文件:http://courses.cs.washington.edu/courses/cse142/16au/homework/names.txt
public static void fileSearch() throws FileNotFoundException {
System.out.println("What name are you looking for?");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
String gender = scan.nextLine();
File file = new File("names.txt");
Scanner fileScan = new Scanner(file);
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
String nameText = lineScan.next();
String genderText = lineScan.next();
if (name.equalsIgnoreCase(nameText) && gender.equalsIgnoreCase(genderText)) {
System.out.println(line);
}
}
}
}