diff options
| author | mo khan <mo@mokhan.ca> | 2019-08-11 15:59:50 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2019-08-11 15:59:50 -0600 |
| commit | a117798660cf949ddc12f335fc547141a0f3d53f (patch) | |
| tree | 146681661622530cc28ddb816cb1e70ede8d922c /src/Q10/TrainTimeTable.java | |
| parent | a70558eb11c09c510897032a04143a79e7dd72a9 (diff) | |
add some error handling
Diffstat (limited to 'src/Q10/TrainTimeTable.java')
| -rw-r--r-- | src/Q10/TrainTimeTable.java | 63 |
1 files changed, 43 insertions, 20 deletions
diff --git a/src/Q10/TrainTimeTable.java b/src/Q10/TrainTimeTable.java index 52992e4..a28952b 100644 --- a/src/Q10/TrainTimeTable.java +++ b/src/Q10/TrainTimeTable.java @@ -16,11 +16,12 @@ public class TrainTimeTable { public void delay(String city, int minutes) { Station station = stationIn(city); - if (station != null) { - station.delayBy(minutes); - for (int i = schedule.indexOf(station) + 1; i < schedule.size(); i++) { - schedule.get(i).delayBy(minutes); - } + if (station == null) + throw new IllegalArgumentException(String.format("`%s` is not on the schedule", city)); + + station.delayBy(minutes); + for (int i = schedule.indexOf(station) + 1; i < schedule.size(); i++) { + schedule.get(i).delayBy(minutes); } } @@ -68,23 +69,45 @@ public class TrainTimeTable { if (selection == null) { System.out.println(); System.out.println("Enter command (Show, Delay, Quit):"); - selection = in.nextLine().toLowerCase(); + selection = in.nextLine(); } - - if (selection.equals("quit")) return; - - if (selection.equals("show")) { - schedule.displaySchedule(System.out); - } else { - String[] tokens = selection.split(" "); - - if (tokens.length < 3) continue; - - String city = ""; - for (int i = 1; i < tokens.length - 1; i++) city += tokens[i]; - schedule.delay(city, Integer.parseInt(tokens[tokens.length - 1])); + String[] tokens = selection.split(" "); + switch (tokens[0].toLowerCase()) { + case "quit": + System.exit(0); + return; + case "show": + schedule.displaySchedule(System.out); + break; + case "delay": + if (tokens.length < 3) break; + + String city = ""; + for (int i = 1; i < tokens.length - 1; i++) city += tokens[i]; + + try { + String enteredMinutes = tokens[tokens.length - 1]; + + if (!enteredMinutes.matches("\\d+")) { + System.out.println("Invalid minutes entered"); + break; + } + + int minutes = Integer.parseInt(enteredMinutes); + if (minutes > (48 * 60)) { + System.out.println("Invalid minutes entered"); + break; + } + schedule.delay(city, minutes); + } catch (IllegalArgumentException error) { + System.out.println(error.getMessage()); + } + + break; + default: + System.out.println("Unknown command"); + break; } - selection = null; } } |
