-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouteCost.java
More file actions
101 lines (85 loc) · 2.78 KB
/
RouteCost.java
File metadata and controls
101 lines (85 loc) · 2.78 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class RouteCost {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
TreeSet<Link> links = new TreeSet<>();
//Take the input in one line
String line = inp.nextLine();
//Convert into tokens
StringTokenizer st = new StringTokenizer(line, " ");
//loop until the user enters done or there are more than 2 inputs
if ((st.countTokens() == 3 || st.countTokens() == 4 || st.countTokens() == 1)) {
//run the loop until the user enters "done"
while (!line.startsWith("done")) {
//brake the input by the user into tokens and use one-by-one
st = new StringTokenizer(line, " ");
City c1 = City.find(st.nextToken());
String length = st.nextToken();
int len;
if(isInteger(length)){
len = Integer.parseInt(length);
}
else{
System.out.println("Invalid line: "+line);
break;
}
City c2 = City.find(st.nextToken());
//adding the color value to the links
if (st.countTokens() == 1) {
String color = st.nextToken().toLowerCase();
if (color.equals("red") || color.equals("blue")) {
Link l1 = new Link(c1, c2, len, color);
} else {
System.out.println("Invalid Line: " + line);
break;
}
} else {
Link l = new Link(c1, c2, len);
}
line = inp.nextLine();
}
//check in the link list if the cities entered by the user already exists or not
for (String name = inp.next(); !name.equals("done"); name = inp.next()) {
City c = City.find(name);
c.makeTree();
if (!c.getLinksTo(City.find(inp.next()), links)) {
System.out.println("Error: Route not found! " + name);
return;
}
}
//print the lists
int total = 0;
System.out.println("The rail network consists of:");
for (Link l : links) {
System.out.println(" "+l);
total += l.getLength();
}
System.out.println("The total cost is: " + total);
} else {
System.out.println("Invalid line: " + line);
}
}
/**
* This method checks if the string passed is an integer or a string
* @param str
* @return boolean
*/
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
int strLength = str.length();
if (strLength == 0) {
return false;
}
for (int i = 0; i < strLength; i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
}