Question 3
Back to Exercise
Write an abstract DocumentParser whose final parse(text) splits records, skips blanks, calls abstract parseRecord and counts errors; implement CsvParser and KeyValueParser.
Solution
import java.util.ArrayList;
import java.util.List;
abstract class DocumentParser {
private int errors;
final List<String> parse(String text) {
List<String> out = new ArrayList<>();
for (String rec : text.split(separator())) {
if (rec.isBlank()) continue;
String r = parseRecord(rec.strip());
if (r == null) errors++; else out.add(r);
}
return out;
}
int errors() { return errors; }
protected String separator() { return "\n"; }
protected abstract String parseRecord(String record); // null = invalid
}
class CsvParser extends DocumentParser {
@Override protected String parseRecord(String rec) {
String[] f = rec.split(",");
return f.length == 3 ? f[0] + " (" + f[1] + ") scored " + f[2] : null;
}
}
class KeyValueParser extends DocumentParser {
@Override protected String separator() { return ";"; }
@Override protected String parseRecord(String rec) {
int eq = rec.indexOf('=');
return eq > 0 ? rec.substring(0, eq).strip().toUpperCase() + " -> " + rec.substring(eq + 1).strip() : null;
}
}
public class Main {
public static void main(String[] args) {
DocumentParser csv = new CsvParser();
System.out.println(csv.parse("Asha,CSE,91\n\nRavi,ECE\nMeena,ME,84") + " errors=" + csv.errors());
DocumentParser kv = new KeyValueParser();
System.out.println(kv.parse("host = localhost; port=8081 ; debug; =x") + " errors=" + kv.errors());
}
}
[Asha (CSE) scored 91, Meena (ME) scored 84] errors=1 [HOST -> localhost, PORT -> 8081] errors=2
The pipeline (splitting, skipping blanks, counting errors) is shared; each parser supplies only its record format and separator.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!