如何显示与用户输入匹配的行?

问题描述 投票:1回答:1

我打算让用户通过选择1-5来选择他们想要过滤的内容。如果用户选择1,则程序应要求他们输入要过滤的年份,此后,应检查输入的长度,如果等于4,则应检查文本文件是否包含以下行:匹配输入。但是如果用户输入等于4位的2019,该记录和否记录将同时显示。如果我只希望仅显示用户输入的年份没有此类记录怎么办?在文本文件中?

textfile

private static void searchForName() throws IOException {
     int choice=0;
     Scanner sc = new Scanner(System.in); 

     System.out.println("_____________________________________________");
     System.out.println("                Filter                ");
     System.out.println("_____________________________________________");
     System.out.println("1 > Filter by Year.");
     System.out.println("2 > Filter by ID.");
     System.out.println("3 > Filter by Name.");
     System.out.println("4 > Filter by Course");
     System.out.println("5 > Exit");
     System.out.println("_____________________________________________");
     System.out.println("Please choose the number:");
     System.out.print(">");
     {
         choice = sc.nextInt();

         if (choice == 1) 
         {
             System.out.println("  Please enter Year you wish to Filter   ");
             Scanner kb = new Scanner(System.in);
             String input = kb.nextLine();

             if(Utility.numberOrNot(input) && (input.length() == 4))
             {                                
                 List<String> lines = Files.readAllLines(Paths.get("C:\\assignment\\student.txt"));
                 for(String line:lines)
                 {
                     if(line.contains(input))
                     {
                         System.out.println(line);
                     }
                     else
                     {
                         System.out.println("No record");
                     }
                 }
             }
             else
             {
                 System.out.println("Sorry!!!!Please enter 4 digit integer...");           
             }                               
         }    

        class Utility
        {
            static boolean numberOrNot(String input)
            {
                try
                {
                    Integer.parseInt(input);
                }
                catch(NumberFormatException ex)
                {
                    return false;
                }
                return true;
            }
        }
    }
}
java
1个回答
1
投票

这是导致您不喜欢的行为的代码部分:

© www.soinside.com 2019 - 2024. All rights reserved.