java Scanner只识别文本文件中的某些行,而不识别其他行
我为这个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);
}
}
}
}
共 (0) 个答案