Solution to the trains problem in Java