Reputation: 61
I need some help with a program that must read in the specified text file and then validate its contents. The results of each valid match should be output to the console (stdout) in the following format:
HomeTeamName [HomeTeamScore] | AwayTeamName [AwayTeamScore]
At the end of the output I need to have generated statistics showing the total number of valid and invalid matches that were processed. Also i need it to show the total number of goals that were scored.
The code I have so far is:
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.
}
}
The sample input file is:
Aston Villa : Middlesbrough : 3 : 1
Chelsea : Manchester City : 1 // only 3 fields provided
Tottenham Hotspur : Stoke City : 0 : 0
Hull : : 2 : 3 // missing away team name
West Ham United : Wigan Athletic : 2 : 1
: : 2 : 0 // both team names missing
Fulham : Liverpool : 1 : 2
Arsenal Liverpool : 2 : 2 // missing delimiter (:) between teams
Sunderland : Newcastle United : 0 : 4
Hull : Liverpool : 5 : x // ‘x’ given instead of away team score
Upvotes: 1
Views: 7051
Reputation: 729
Seems like this would be pretty easy with java.util.regex.Pattern. Just construct a regex pattern for the valid record format. Then create a matcher for each of the lines you read and see if it matches. If it does, then output that line.
Something like (pseudo java code):
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");
}
}
Option w/o regular expressions:
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...
}
Given the choice between the two above, I would use expressions. It's more expressive than slogging through a bunch of if/else code. There are also libraries like BeanIO that do a lot of this stuff for you.
Upvotes: 1