Train Schedule example – Java snippet

We were asked lately, by one of our readers to help him with train schedule code which he needed for his application. The requirements for this code where as follows: the first train leaves at 6:00 am each day and the last train leaves at 23.00 pm. Trains run every 7 minutes. Those three values are not coded into our solution literally and can be provided as the constructor parameters.

ITCuties - TrainSchedule - Java snippet

ITCuties – TrainSchedule – Java snippet

It was a great programming skill practice task. Here is the code.

TrainSchedule class Java snippet

package com.itcuties.java.snippets;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Sample Train Schedule implementation.
 * 
 * @author itcuties
 *
 */
public class TrainSchedule {

	// Train schedule
	private List<Date> schedule;
	
	/**
	 * Initialize object
	 * 
	 * @param trainFrequency - in minutes
	 * @param firstTrain - date of the first train
	 * @param lastTrain - date of the last train
	 */
	public TrainSchedule(short trainFrequency, Date firstTrain, Date lastTrain) {
		schedule = new ArrayList<Date>();
		
		// Train frequency in milliseconds
		long trainFrequencyMillis = trainFrequency*60*1000;
		
		// First and last train date in milliseconds
		long firstTrainMillis	  = firstTrain.getTime();
		long lastTrainMillis	  = lastTrain.getTime();
		
		
		// Iterate from the first train date to the last train date to initialize the schedule
		for (long i=firstTrainMillis; i < lastTrainMillis; i += trainFrequencyMillis) {
			schedule.add(new Date(i));
		}
		
		// Add the last train literally
		schedule.add(lastTrain);
	}

	/**
	 * Return time to next train in milliseconds
	 * @param time
	 * @return
	 */
	public long timeToNextTrain(Date time) {
		// Current time in milliseconds
		long currentTime = time.getTime();
		
		// Check if the trains are riding
		if (currentTime <= schedule.get(0).getTime()) // You are before the first train
			return schedule.get(0).getTime() - currentTime; // Time to the first train
		
		if (currentTime >= schedule.get(schedule.size()-1).getTime()) {	// You are after the last train
			// You need to take the first train from the next day schedule
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(schedule.get(0).getTime() + 24*60*60*1000); // Set the next schedule first train time using this schedule first train time + one day in milliseconds
			
			return calendar.getTimeInMillis() - currentTime;
		}
		
		// We are in the schedule - go through it
		for (int i=0; i < schedule.size(); i++) {
			if (i == schedule.size() - 1) // We are at the last element, need to brake the loop
				break;
			// Time of the previous and next trains
			long previous = schedule.get(i).getTime();
			long next     = schedule.get(i+1).getTime();
			
			if (currentTime > previous && currentTime < next)
				return next - currentTime;
			
		}
		
		// Should never happen :)
		return -1;
	}
	
	/**
	 * Get the train schedule.
	 * @return
	 */
	public List<Date> getSchedule() {
		return schedule;
	}
}

You can define the train schedule using the constructor – public TrainSchedule(short trainFrequency, Date firstTrain, Date lastTrain). Just provide the first train and last train departure time and the time gap between the trains. When the TrainSchedule is created call the timeToNextTrain, providing it a Date, to get the number of milliseconds you have till the next train leaves.

Here is a sample class usage.

TrainSchedule class usage

	// Set the calendar to 06:00 AM today
	Calendar calendar = Calendar.getInstance();
	calendar.set(Calendar.HOUR_OF_DAY, 6);
	calendar.set(Calendar.MINUTE, 0);
	calendar.set(Calendar.SECOND, 0);
	calendar.set(Calendar.MILLISECOND, 0);
		
	// The time of the first train
	Date firstTrain = calendar.getTime();
		
	// Let's change the hour 
	calendar.set(Calendar.HOUR_OF_DAY, 23);
	Date lastTrain = calendar.getTime();
		
	// Create the TrainSchedule object
	TrainSchedule ts = new TrainSchedule((short)7, firstTrain, lastTrain);
		
	// Display the schedule
	System.out.println("Today's schedule:");
	for (Date d: ts.getSchedule())
		System.out.println(d);
		
	System.out.println("=========================================");
		
	calendar = Calendar.getInstance();
	// Let's check how much time we have to the next train
	System.out.println("It's " + calendar.getTime() + " you have " + ts.timeToNextTrain(calendar.getTime()) / 1000 + " seconds to the next train");
		
	// Let's check how it would behave when we are before the schedule
	calendar.set(Calendar.HOUR_OF_DAY, 5);
	System.out.println("It's " + calendar.getTime() + " you have " + ts.timeToNextTrain(calendar.getTime()) / 1000 + " seconds to the first train from today's schedule");
		
	// Let's check how it would behave when we are before the schedule
	calendar.set(Calendar.HOUR_OF_DAY, 23);
	System.out.println("It's " + calendar.getTime() + " you have " + ts.timeToNextTrain(calendar.getTime()) / 1000 + " seconds to the first train from the next schedule");
		

In this code we create a schedule where, following the original requirements, the first train leaves at 06.00 AM, the last train departure time is 23:00 PM and trains run every 7 minutes. Next we check 3 dates – one before the first train leaves, the second one is during the time when trains run, and the last date is after trains stop running.

The result of running this code is something like this (depending on when you run it :))

Today's schedule:
Fri Jun 21 06:00:00 CEST 2013
Fri Jun 21 06:07:00 CEST 2013
Fri Jun 21 06:14:00 CEST 2013
Fri Jun 21 06:21:00 CEST 2013
Fri Jun 21 06:28:00 CEST 2013
Fri Jun 21 06:35:00 CEST 2013
Fri Jun 21 06:42:00 CEST 2013
Fri Jun 21 06:49:00 CEST 2013
...
..
.
Fri Jun 21 21:17:00 CEST 2013
Fri Jun 21 21:24:00 CEST 2013
Fri Jun 21 21:31:00 CEST 2013
Fri Jun 21 21:38:00 CEST 2013
Fri Jun 21 21:45:00 CEST 2013
Fri Jun 21 21:52:00 CEST 2013
Fri Jun 21 21:59:00 CEST 2013
Fri Jun 21 22:06:00 CEST 2013
Fri Jun 21 22:13:00 CEST 2013
Fri Jun 21 22:20:00 CEST 2013
Fri Jun 21 22:27:00 CEST 2013
Fri Jun 21 22:34:00 CEST 2013
Fri Jun 21 22:41:00 CEST 2013
Fri Jun 21 22:48:00 CEST 2013
Fri Jun 21 22:55:00 CEST 2013
Fri Jun 21 23:00:00 CEST 2013
=========================================
It's Fri Jun 21 22:54:46 CEST 2013 you have 13 seconds to the next train
It's Fri Jun 21 05:54:46 CEST 2013 you have 313 seconds to the first train from today's schedule
It's Fri Jun 21 23:54:46 CEST 2013 you have 21913 seconds to the first train from the next schedule

Download this sample code here.

This code is available on our GitHub repository as well.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>