Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package dailyprogrammer.medium.averagespeedcameras;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.time.LocalTime;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
- public class LogParser {
- private List<CameraLog> cameras;
- private double limit;
- Set<String> cars;
- private DistMeasure distMeasure;
- LogParser() {
- this.cameras = new ArrayList<>();
- this.cars = new HashSet<>();
- }
- public List<CameraLog> parseLog(File logFile) throws Exception {
- try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
- readSpeedLimit(reader);
- readCameras(reader);
- readCameraLogs(reader);
- }
- return cameras;
- }
- private void readSpeedLimit(BufferedReader reader) throws Exception {
- String line = reader.readLine();
- String[] tokens = line.split(" ");
- limit = Double.parseDouble(tokens[3]);
- distMeasure = tokens[4].equals("mph.") ? DistMeasure.MP : DistMeasure.KM;
- }
- private void readCameras(BufferedReader reader) throws Exception {
- for (;;) {
- reader.mark(50);
- String line = reader.readLine();
- if (line.matches("Speed camera number [\\d]+ is [\\d]+ metres down the motorway.")) {
- int dist = Integer.parseInt(line.split(" ")[5]);
- cameras.add(new CameraLog(dist));
- } else {
- reader.reset();
- break;
- }
- }
- }
- private void readCameraLogs(BufferedReader reader) throws Exception {
- CameraLog camera = cameras.get(0);
- String line;
- while ((line = reader.readLine()) != null) {
- if (line.matches("Start of log for camera [\\d]+.")) {
- int index = Integer.parseInt(line.split("[ \\.]")[5]);
- camera = cameras.get(--index);
- } else {
- String[] tokens = line.split(" ");
- String carNum = tokens[1] + " " + tokens[2];
- cars.add(carNum);
- LocalTime camPassed = LocalTime.parse(tokens[7]);
- camera.addToLog(carNum, camPassed);
- }
- }
- }
- public double getSpeedLimit() {
- return limit;
- }
- public Set<String> getCars() {
- return cars;
- }
- public List<CameraLog> getCameras() {
- return cameras;
- }
- public DistMeasure getDistMeasure() {
- return distMeasure;
- }
- static enum DistMeasure {
- KM,
- MP;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement