我需要一个程序的帮助,该程序必须读取指定的文本文件,然后验证其内容。每次有效匹配的结果都应以以下格式输出到控制台(stdout):
HomeTeamName [HomeTeamScore] | AwayTeamName [AwayTeamScore]
在输出的末尾,我需要生成统计信息,以显示已处理的有效和无效匹配的总数。我也需要它来显示进球总数。
到目前为止,我的代码是:
public class Generator {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("results.txt"));
String line;
while ( s.hasNext() ) {
line = s.nextLine();
System.out.println(line);
}
System.out.println("\nEOF"); // Output and End Of File message.
}
}
样本输入文件是:
阿斯顿维拉:米德尔斯堡:3:1
切尔西:曼城:1 //仅提供了3个区域
托特纳姆热刺:斯托克城:0:0
船体::2:3 //客队名字
西汉姆联:威根竞技:2: 1
::2:0 //缺少两个球队名称
富勒姆:利物浦:1:2
阿森纳利物浦:2:2 //缺少队之间的定界符(:)
桑德兰:纽卡斯尔联:0:4
船体:利物浦:5:x /'x'代替客队得分
使用java.util.regex.Pattern似乎很容易。只需为有效的记录格式构造一个正则表达式模式即可。然后为您阅读的每一行创建一个匹配器,看看是否匹配。如果是这样,则输出该行。
类似于(伪Java代码)的东西:
Pattern pattern = Pattern.compile("your regular expression here");
while((line = readLine()) != null) {
Matcher m = pattern.matcher(line);
if (m.matches()) {
System.out.println(line + " is good");
} else {
System.out.println(line + " is not good");
}
}
不带正则表达式的选项:
while((line = readLine()) != null) {
String[] values = line.split(":");
if (values.length != 4) {
System.out.println("bad line: " + line);
}
// check for empty fields like:
if (values[0].isEmpty()) {/* error message */}
// check for proper numeric values like:
try {
// prob need to remove leading whitespace as well...
Integer.parseInt(values[2].trim());
} catch (NumberFormatException e) {/* error message */}
// etc...
}
鉴于以上两者之间的选择,我将使用表达式。它比一堆if / else代码更具表现力。还有像BeanIO这样的库,可以为您做很多事情。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句