-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlightLoader.java
More file actions
82 lines (73 loc) · 2.71 KB
/
Copy pathFlightLoader.java
File metadata and controls
82 lines (73 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// --== CS400 Project Three File Header ==--
// Name: Bill Zhu
// CSL Username: bzhu
// Email: wlzhu@wisc.edu
// Lecture #: 002 @1:00pm
// Notes to Grader:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class that reads and parses the JSON file, returning a list of Path objects
*
* @author williamzhu
*
*/
public class FlightLoader implements IFlightLoader {
/**
* Parses the JSON file and returns a list of the path objects.
*/
public List<IPath> loadFlightPaths(String filepath) throws FileNotFoundException {
List<IPath> paths = new ArrayList<IPath>(); // List to return
File flightPaths = new File(filepath); // File to look in
Scanner fileReader = new Scanner(flightPaths); // Scans the file to look in.
String line = ""; // Temporary storing variable for each line.
// Edge case: No applicable file to look in. Throws an exception
if (!flightPaths.exists()) {
throw new FileNotFoundException("File does not exist.");
}
// Iterates through each line of the file.
while (fileReader.hasNext()) {
line = fileReader.nextLine();
// Temporary variables to store parsed data in order to create a path file
String origin = "";
String destination = "";
int distance = 0;
// Edits out the useless beginning and ending lines
if (line.equals("["))
line = fileReader.nextLine();
if (line.equals("]"))
return paths;
// Parses the line and extracts the important information (Origin airport, destination
// airport, and distance between the two).
for (String arg : line.split(",")) {
String[] keyValuePair = arg.split(":");
switch (keyValuePair[0]) {
// Parses the origin airport data.
case "{\"ORIGIN_AIRPORT\"":
origin = keyValuePair[1].substring(1, keyValuePair[1].length() - 1);
break;
// Parses the destination airport data.
case "\"DESTINATION_AIRPORT\"":
destination = keyValuePair[1].substring(1, keyValuePair[1].length() - 1);
break;
// Parses the distance data.
case "\"DISTANCE\"":
Pattern distances = Pattern.compile("\\d+");
Matcher distanceMatcher = distances.matcher(line);
distanceMatcher.find();
distance = Integer.parseInt(distanceMatcher.group());
break;
}
}
// Creates a path object with the temporary variables and adds it to the list.
IPath path = new Path(origin, destination, distance);
paths.add(path);
}
return paths;
}
}