Advertisement
ridjis

Train

Mar 29th, 2016
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. public class Trains {
  2.     private Map<String, TrainInfo> trains;
  3.    
  4.     public Trains() {
  5.         trains = new HashMap<>();
  6.     }
  7.    
  8.     public void process() throws IOException {
  9.         BufferedReader in = null;
  10.         try {
  11.             InputStream stream = Trains.class.getResourceAsStream("trainlog.txt");
  12.             in = new BufferedReader(new InputStreamReader(stream));
  13.            
  14.             String line;
  15.            
  16.             while ((line = in.readLine()) != null) {
  17.                 String[] data = line.split(";");
  18.                
  19.                 boolean arrival = data[1].trim().equals("arrival");
  20.                 String id = data[0].trim();
  21.                
  22.                 TrainInfo train = trains.get(id);
  23.                 if (train == null) {
  24.                     if (arrival) {
  25.                         System.err.println("There is no arrival for the train " + id);
  26.                         System.exit(-1);
  27.                     }
  28.                    
  29.                     train = new TrainInfo(id);
  30.                     trains.put(id, train);
  31.                 }
  32.                
  33.                 int time = Integer.parseInt(data[2].trim());
  34.                 if (arrival)
  35.                     train.arrived(time);
  36.                 else
  37.                     train.departed(time);
  38.             } // end while()
  39.            
  40.             print();
  41.         } finally {
  42.             if (in != null)
  43.                 in.close();
  44.         }
  45.     }
  46.    
  47.     private void print() {
  48.         Set<TrainInfo> set = new TreeSet<>();
  49.         set.addAll(trains.values());
  50.        
  51.         for (TrainInfo t: set)
  52.             System.out.println(t);
  53.     }
  54.    
  55.     public static void main(String[] args) throws IOException {
  56.         new Trains().process();
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement