Parsing strings using split, Example 2
Code developed in-class Tuesday, May 6, as well as some additional code
public static boolean fileVerifier(String fileName) {
try {
File inFile = new File(fileName);
Scanner in = new Scanner(inFile);
boolean isValid = true;
int lineNum = 0; // current line #
// read in each line in the file and check it for validity
while (in.hasNext()) {
String line = in.nextLine();
lineNum++;
isValid = validLine(line, lineNum) && isValid;
}
// post-condition: isValid is true only if each line in
// the file is valid
in.close(); // close the scanner (and file)
return isValid;
} catch (FileNotFoundException fnfe) {
System.out.println("File not found");
return false;
}
}
/**
* Private helper method used to check a single line for validity.
* Note that if a line contains more than one error, only the first error
* detected results in an error message (and the method then returns false,
* i.e., the rest of the line is not checked).
*
* @param line the line to check
* @param lineNum the line # (used when printing error messages)
*/
private static boolean validLine(String line, int lineNum) {
// each line should contain 3 pieces of information (day, time, temp)
// separated by one or more spaces
String[] tokens = line.split("[ ]+");
// if there aren't exactly 3 tokens, there is an error
if (tokens.length != 3) {
System.out.println("line " + lineNum +
": # pieces of info incorrect");
return false;
}
// check day, time, and temp for correct format, printing out
// an error message if a format is incorrect
if (!validDay(tokens[0])) {
System.out.println("line " + lineNum + " : invalid day");
return false;
}
if (!validTime(tokens[1])) {
System.out.println("line " + lineNum + " : invalid time");
return false;
}
if (!validTemp(tokens[2])) {
System.out.println("line " + lineNum + " : invalid temp");
return false;
}
// if we've gotten here, everything was ok, so return true
return true;
}
// STILL TO DO
private static boolean validDay(String str) {
}
private static boolean validTime(String str) {
}
private static boolean validTemp(String str) {
}