【问题标题】:Method never reaching an if statement despite, its conditions being met尽管满足其条件,但方法从未达到 if 语句
【发布时间】: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

这个程序的逻辑错误在哪里?

【问题讨论】:

    标签: java methods return


    【解决方案1】:

    为什么程序会回到第一个 while 循环并开始扫描列表中的其余名称,尽管找到了匹配项?

    因为你调用了两次该方法:

    searchInfo (input, userName, userGender);
    System.out.print(searchInfo (input, userName, userGender));
    

    您必须跳过第一次调用或将第一次调用的结果存储在一个变量中,而不是第二次调用该方法打印该变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      相关资源
      最近更新 更多