读取文本文件中的数字并计算java中的总数

时间:2014-11-07 18:27:05

标签: java file-io

我是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());

        }


    }

}

我试图自己做,但是无法理解,任何帮助都会非常感激,谢谢!

3 个答案:

答案 0 :(得分:0)

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

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

保留

答案 1 :(得分:0)

试试这个:

 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());

    }


}

}

答案 2 :(得分:0)

我建议你制作方法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