【问题标题】:Calling on a Method to Display Output Names from Chat Log调用方法以显示聊天日志中的输出名称
【发布时间】:2017-07-10 16:27:09
【问题描述】:

我在将方法实现为一些输出代码时遇到了麻烦。本质上,我创建了一个名为getName 的方法,它将人名分配给一个唯一编号。然后,我得到一个包含聊天日志的输入文件。在我过滤掉我需要的行后,我需要它能够显示人的姓名而不是号码。这是我的方法的一个sn-p:

public static String getName(int id) {
        // External identifiers specified
        switch (id) {
        case 5644:
            return "Steve Jobs";
        case 5640:
            return "John Smith";
        case 5663:
            return "Johnny Appleseed";

这是接受我的输入并显示我需要的输出的代码:

try
  {
  // assigns the input file to a filereader object
     BufferedReader infile = new BufferedReader(new FileReader(log));

      sc = new Scanner(log);
            while(sc.hasNext())
              {
                 String line=sc.nextLine();
                   if(line.contains("LANTALK")){
                    Pattern pattern = Pattern.compile("
                    (\\d{2}:\\d{2}:\\d{2}\\.\\d{3})\\s\\[D\\].+<MBXID>(\\d+)
                    <\\/MBXID><MBXTO>(\\d+)<\\/MBXTO>.+<MSGTEXT>(.+)
                    <\\/MSGTEXT>", Pattern.MULTILINE + Pattern.DOTALL); 
                    // Multiline is used to capture the LANMSG more than 
                    once, and Dotall is used to make the '.' term in regex 
                    also match the newline in the input
                Matcher matcher = pattern.matcher(line);
                while (matcher.find())
                    {
                       String output = matcher.group(1) + " [" + 
                       matcher.group(2) + "] to [" + matcher.group(3) + "] " 
                       + matcher.group(4);
                       System.out.println(output);
                       System.out.println();
                    }

                   } // End of if

               } // End of while

每行输出如下所示:

14:49:28.817 [1095] to [5607] I could poke around with it a bit and see what's available.

我只需要数字10955607 来显示我在方法中指定的人名。所以我问我如何在我的代码中实现它?是否有一种特殊的方式需要我调用该方法才能识别数字?我是否使用某种正则表达式或 XML?感谢您的帮助!

【问题讨论】:

    标签: java regex xml methods


    【解决方案1】:

    您应该使用字典

    使用字典的好处:

    • 您将能够以键值对的形式访问用户名和他们的 ID 号。
    • 他们很快。
    • 您将无需使用 switch 语句来跟踪用户 ID。

    链接:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多