【问题标题】:Read numbers in a text file and calculate total in java读取文本文件中的数字并在 java 中计算总数
【发布时间】:2014-11-08 03:37:47
【问题描述】:

我是 java 初学者,一直在开发一个可以读取文本文件的程序。 文本文件如下所示:

Chicago Fire : FC Dallas : 2 : 2
LA Galaxy : Toronto FC : 1 : 3
Real Salt Lake : DC United : 3 : 2
Colorado Rapids : Columbus Crew : 0 : 0
Sporting Kansas City : New York Red Bulls : 2 : 1

我希望我的代码读取文件中的所有数字,然后在末尾显示总金额,如下所示:

Chicago Fire : FC Dallas : 2 : 2
LA Galaxy : Toronto FC : 1 : 3
Real Salt Lake : DC United : 3 : 2
Colorado Rapids : Columbus Crew : 0 : 0
Sporting Kansas City : New York Red Bulls : 2 : 1

Total goals = 16

到目前为止我的代码:

public void showResults(){

        String separator = ":";
        File inputfile = new File ("result.txt");

        String[] StrArray;
        String aLine = "";

        System.out.println ("Home team         "+"\tHome score" + "                                   " + "\t Away Team" + "\t Away Score  \n=============================================================================" );

        try {
            Scanner filescan = new Scanner(inputfile);
            while (filescan.hasNext()){
                aLine = filescan.nextLine();
                StrArray = aLine.split(separator);


                if (StrArray.length == 4){
                    System.out.println (StrArray[0] +"\t" + StrArray [2]  +  StrArray[1] + "\t" + StrArray[3]);
                } else {
                    throw new IllegalArgumentException("Invalid match count : "+ aLine );
                }

            }

            filescan.close();


        } 

        catch (FileNotFoundException e)
        {
            System.out.println("problem "+e.getMessage());

        }


    }

}

我尝试自己做,但无法弄清楚,任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 尽可能使用xml。您可以轻松维护数据。
  • 你的问题是什么?您的代码在哪里没有达到您的预期?

标签: java file-io


【解决方案1】:

我建议你创建 static 方法,使用 try-with-resources,传入 filePath 进行读取,使用格式化输出和类似空白空格的模式,

public static void showResults(String filePath) {
    String separator = "\\s*:\\s*";
    File inputfile = new File(filePath);
    String[] heading = { "Home team", "Home score", "Away team",
            "Away score" };
    for (int i = 0; i < heading.length; i++) {
        String fmt = "%20s ";
        if (i % 2 != 0)
            fmt = "%12s ";
        System.out.printf(fmt, heading[i]);
    }
    System.out.println();
    for (int i = 0; i < 68; i++) {
        System.out.print('=');
    }
    System.out.println();
    int goals = 0;
    try (Scanner filescan = new Scanner(inputfile);) {
        while (filescan.hasNext()) {
            String aLine = filescan.nextLine();
            String[] tokens = aLine.split(separator);
            if (tokens.length == 4) {
                System.out.printf("%20s %12s %20s %12s%n", tokens[0],
                        tokens[2], tokens[1], tokens[3]);
                goals += Integer.parseInt(tokens[2]);
                goals += Integer.parseInt(tokens[3]);
            } else {
                throw new IllegalArgumentException("Invalid match count : "
                        + aLine);
            }
        }
    } catch (FileNotFoundException e) {
        System.out.println("problem " + e.getMessage());
    }
    System.out.printf("%nTotal goals = %d%n", goals);
}

当我在这里运行上面的代码时,我得到了(请求的)输出

           Home team   Home score            Away team   Away score 
====================================================================
        Chicago Fire            2            FC Dallas            2
           LA Galaxy            1           Toronto FC            3
      Real Salt Lake            3            DC United            2
     Colorado Rapids            0        Columbus Crew            0
Sporting Kansas City            2   New York Red Bulls            1

Total goals = 16

【讨论】:

    【解决方案2】:

    这是一个简单的初学者解决方案:

    int total=0;
    while (filescan.hasNext()){
            aLine = filescan.nextLine();
            StrArray = aLine.split(separator);
    
            if (StrArray.length == 4){
                System.out.println (StrArray[0] +"\t" + StrArray [2]  +  StrArray[1] + "\t" + StrArray[3]);
                total += Integer.parseInt(StrArray[3]);  // will return the integer value of the s
                total+= Integer.parseInt(StrArray[4]);
            } else {
                throw new IllegalArgumentException("Invalid match count : "+ aLine );
            }                  
    
           }
    
     }
    

    提示: - 不要用大写字母命名变量,应该为类保留 (StrArray)

    【讨论】:

      【解决方案3】:

      试试这个:

       public void showResults(){
      
          String separator = ":";
          File inputfile = new File ("result.txt");
          int totalgoal=0;
          String[] StrArray;
          String aLine = "";
      
          System.out.println ("Home team         "+"\tHome score" + "                                   " + "\t Away Team" + "\t Away Score  \n=============================================================================" );
      
          try {
              Scanner filescan = new Scanner(inputfile);
              while (filescan.hasNext()){
                  aLine = filescan.nextLine();
                  StrArray = aLine.split(separator);
      
      
                  if (StrArray.length == 4){
                      System.out.println (StrArray[0] +"\t" + StrArray [2]  +  StrArray[1] + "\t" + StrArray[3]);
                      totalgoal+=Integer.parseInt(StrArray[2]);
                      totalgoal+=Integer.parseInt(StrArray[3]);
                  } else {
                      throw new IllegalArgumentException("Invalid match count : "+ aLine );
                  }
      
              }
      
              filescan.close();
              System.out.println ("Total goals ="+String.valueOf(totalgoal));  
      
          } 
      
      
          catch (FileNotFoundException e)
          {
              System.out.println("problem "+e.getMessage());
      
          }
      
      
      }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2013-11-25
        • 2015-02-02
        • 1970-01-01
        • 1970-01-01
        • 2018-07-22
        • 2016-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多