From a117798660cf949ddc12f335fc547141a0f3d53f Mon Sep 17 00:00:00 2001 From: mo khan Date: Sun, 11 Aug 2019 15:59:50 -0600 Subject: add some error handling --- src/Q10/TrainTimeTable.java | 63 +++++++++++++++++++++++++++++++-------------- 1 file changed, 43 insertions(+), 20 deletions(-) (limited to 'src/Q10/TrainTimeTable.java') 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; } } -- cgit v1.2.3