【发布时间】:2020-05-22 07:57:05
【问题描述】:
我正在尝试扫描带有姓名和性别的 txt.file,我的代码应该接受用户输入的姓名和性别,通读 txt 文件以查看该组合是否存在,然后返回信息(如果匹配)或说不匹配。 我放置占位符 S.O.P 语句只是为了帮助调试,它表明它到达了 return 语句,它应该从 txt 文件中返回信息,因为它找到了匹配项,但是该方法无法传递返回用户的 if 语句一旦有匹配的信息,即使用户输入的信息应该是匹配的。 代码在这里:
public class Draft {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
Scanner input = new Scanner(new File("names.txt"));
ProgramIntro();
System.out.print("name? ");
String userName = console.nextLine();
System.out.print("sex (M or F)? ");
String userGender = console.nextLine();
System.out.print(searchInfo (input, userName, userGender));
}
//searches file for user input match and returns value depending on whether a match exists
public static String searchInfo (Scanner input, String userName, String userGender) {
//goes through the file until there are no more entries
while (input.hasNextLine()) {
System.out.print("blach");
//concatenates one line of file into one string
String line = input.nextLine();
//turns the focus into just one line
Scanner lineScan = new Scanner(line);
//runs loop just on one single line
while (!lineScan.hasNextInt()) {
System.out.print("bafdjkf");
//sets the first thing in a line (the name) as String babyName
String babyName = lineScan.next();
System.out.print(babyName);
//sets the first thing in a line (the name) as String gender
String gender = lineScan.next();
System.out.println(gender);
if (userName.equalsIgnoreCase(babyName) && userGender.equalsIgnoreCase(gender)) { //THE PROBLEM LINE
System.out.print("jgfgfgfgfgfg");
System.out.println(line);
return line;
}
}
}
return "name/sex combination not found";
}
它永远不会到达 if 语句,因为 if 语句中的占位符 S.O.P 永远不会打印。
blachbafdjkfCaleighF //Caleigh is the name we tested
blachbafdjkfRisaF
blachbafdjkfRoninM
blachbafdjkfFronaF
blachbafdjkfDanaF
blachbafdjkfJesusM
blachbafdjkfHarleyM
blachbafdjkfJadaF
这个程序的逻辑错误在哪里?
【问题讨论】: