如何计算文件中的有效行和无效行

时间:2014-11-08 13:22:20

标签: java validation unit-testing if-statement count

我有以下代码:

public class generator {


public static void main(String[] args) throws FileNotFoundException {


    Scanner s = new Scanner(new File("results.txt"));// creates a scanner to
                                                        // scan from a file
    String line;
    String HomeTeam, AwayTeam;
    while (s.hasNext()) {
        line = s.nextLine(); // reads the next line from the file
        line = line.trim(); // trims the line
        String[] elements = line.split(":"); // splits the line
        if (elements.length == 4) {
            HomeTeam = elements[0].trim(); // trims home team
            AwayTeam = elements[1].trim(); // trims away team
            elements[2] = elements[2].trim();
            elements[3] = elements[3].trim();

            if (HomeTeam.length() != 0 && AwayTeam.length() != 0) { // check if position is present
                try {   // "try" is a special statement which allows us to deal with "exceptions"

                    int HomeScore = Integer.parseInt(elements[2]);  // attempt to convert the String into an Integer type value
                    int AwayScore = Integer.parseInt(elements[3]);
                    System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
                }
                catch (NumberFormatException e) {

                }

            }

        }

    }

}

}

现在我的问题是:我如何计算有效和无效的行以及整个文件中的总分数?

示例输入文件是:
利兹联:利物浦:1:2
切尔西:曼城:1:1
阿斯顿维拉:米德尔斯堡:3:1
托特纳姆热刺:斯托克城:0:0
西汉姆联队:维冈竞技:2:1
富勒姆:利物浦:1:2
维冈竞技:利兹联队:2:2
阿森纳利物浦:2:2
赫尔城:托特纳姆热刺:3:5
埃弗顿:朴茨茅斯:4:2
斯托克城:West Bromwich Albion:5:4
利兹联:利物浦:1:10
布莱克本流浪者:富勒姆:1:1
西汉姆联队:纽卡斯尔联队:0:0
曼联:维冈竞技:1:2
赫尔城:桑德兰:2:3
切尔西:曼城:1 富勒姆:利兹联队:1:2
维冈竞技:托特纳姆热刺:2:2
赫尔城:埃弗顿:3:​​5
:: 2:0
桑德兰:布莱克本流浪者:4:2
斯托克城:West Bromwich Albion:5:4
赫尔:利物浦:5:x
布莱克本流浪者:富勒姆:1:1
切尔西:埃弗顿:a:1 桑德兰:纽卡斯尔联队:0:0
船体:: 2:3
桑德兰:布莱克本流浪者:1:2
赫尔城:埃弗顿:2:3
利兹联:切尔西:1:2
切尔西:曼城:1:1
阿斯顿维拉:富勒姆:3:1
曼城:斯托克城:0:0
西汉姆联队:米德尔斯堡:2:1

4 个答案:

答案 0 :(得分:0)

因此,您需要为您需要的每个指标设置计数器变量。因此,在您的while循环之前将它们定义为:

int totalAwayScore = 0, totalHomeScore = 0, invalidLines = 0, totalLines = 0;

在while循环中,将totalLines增加为

totalLines++; 

表示您有下一行要阅读。您的try catch是您知道得分多少的地方,因此请继续添加您在上面定义的指标,如:

try {   // "try" is a special statement which allows us to deal with "exceptions"
  int HomeScore = Integer.parseInt(elements[2]);  // attempt to convert the String into an Integer type value
  int AwayScore = Integer.parseInt(elements[3]);
  totalAwayScore += AwayScore;
  totalHomeScore += HomeScore;
  System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
} catch (NumberFormatException e) {
    invalidLines++;
}

这里如果你得到数字格式异常,你就会知道它是无效的行,因此增加了在文件中保存无效行的变量的值。

在while循环结束时,您可以打印以下数据:

System.out.println("Total home score is " + totalHomeScore + " totalAway score is " + totalAwayScore + " invalid lines were " + invalidLines + " of total " + totalLines);

答案 1 :(得分:0)

我不确定我理解但是:

  1. 您需要增加catch中无效行的计数器 部分。它表示该行是错误的,因为数字是 不是数字;

  2. 您需要在else部分中增加无效行的计数器 如果

    if (elements.length == 4)

    这意味着你有太多或太多的论点;

  3. 如果HomeTeam和,你需要增加无效行的计数器 AwayTeam是==“”因为你没有球队的名字;

  4. 干杯

答案 2 :(得分:0)

您可以添加两个计数器 - 一个用于所有( allCounter ),另一个用于错误的行( wrongCounter ):

  • 在每个循环迭代增量的开头 allCounter
while (s.hasNext()) {
    allCounter++;
    line = s.nextLine(); // reads the next line from the file
    ...
  • 如果某些内容错误,请递增 wrongCounter 并继续下一轮循环
if (elements.length != 4) {
    ++wrongCounter;
    continue; //breaks this iteration and moves to next one
}
//otherwise proceed normally
homeTeam = elements[0].trim(); // trims home team  
awayTeam = elements[1].trim(); // trims away team
...

同样在第二个 if catch 子句中:

 catch (NumberFormatException e) {
     ++wrongCounter;
 }

当然:

 int correctCounter = allCounter - wrongCounter;

还有一件事:根据Java惯例,您应该使用 camelCase 编写所有变量/方法名称,即以小写字母开头,然后以大写字母开始每个新单词:
示例:不是 HomeTeam ,而是 homeTeam

答案 3 :(得分:0)

实际上你检查有效性以及计算的问题是什么?创建两个变量:ValidNumbInvalidNumb。在ValidNumb之后增加System.out.println()。如果InvalidNumb不等于4,团队名称的长度等于0,则增加elements.length或者在转换得分为整数时捕获异常。
要计算所有分数:再创建一个变量allScores并将其添加到HomeScore块中的AwayScoretry

public static void main(String[] args) throws FileNotFoundException {


    Scanner s = new Scanner(new File("results.txt"));// creates a scanner to
                                                    // scan from a file
    String line;
    String HomeTeam, AwayTeam;
    Int ValidNumb = 0, InvalidNumb = 0; //counters of valid and invalid lines
    Int AllScores = 0; //sum of all goals
    while (s.hasNext()) {
        line = s.nextLine(); // reads the next line from the file
        line = line.trim(); // trims the line
        String[] elements = line.split(":"); // splits the line
        if (elements.length == 4) {
            HomeTeam = elements[0].trim(); // trims home team
            AwayTeam = elements[1].trim(); // trims away team
            elements[2] = elements[2].trim();
            elements[3] = elements[3].trim();

            if (HomeTeam.length() != 0 && AwayTeam.length() != 0) { // check if position is present
                try {   // "try" is a special statement which allows us to deal with "exceptions"

                    int HomeScore = Integer.parseInt(elements[2]);  // attempt to convert the String into an Integer type value
                    int AwayScore = Integer.parseInt(elements[3]);
                    AllScores = AllScores + HomeScore + AwayScore; //sum up scores
                    System.out.println(HomeTeam + " ["+ HomeScore +"]" + " | " + AwayTeam + " ["+AwayScore+"]");
                    ValidNumb++; //line is valid
                }
                catch (NumberFormatException e) {
                    InvalidNumb++; //scores are not integers
                }

            }
            else {InvalidNumb++;} //HomeTeam or AwayTeam are empty

        }
        else {InvalidNumb++;} //not enough elements in line

    }

}