Hi, Trying to get this bit of code to work so that a train goes up the track, leaves the track and then a train comes down the track, leaves and then a train comes up the track and so on. Only one train is allowed to go onto the track at anytime. My output starts off as this
Train 1 entered track, going DOWN
Train 1 left track, going DOWN
Train 7 entered track, going UP
Train 7 left track, going UP
Train 3 entered track, going DOWN
Train 3 left track, going DOWN
Train 6 entered track, going UP
Train 6 left track, going UP
which is right but then turns too
Train 8 left track, going UP
Train 5 left track, going UP
Train 4 left track, going DOWN
Train 2 left track, going DOWN
I have no idea why this is happening and if someone could show me where i have went wrong and why its went wrong i would be greatful.
public class UpDownTrack extends OpenTrack
{
//Add the allowedDirection attribute required
private TrainDirection allowedDir;
//Add a constructor to set the initial state of an UpDOwnTrack
public UpDownTrack()
{
allowedDir = DOWN;
}
// only allows one train on the track
public synchronized void useTrack(TrainDirection trainDir, int id)
{
try
{
enterTrack(trainDir, id);
traverse();
exitTrack(trainDir,id);
}
catch(Exception e)
{
System.out.println("Error" + e);
}
}
// Only allows a train to leave in the opposite direction
public synchronized void enterTrack(TrainDirection trainDir, int id)
{
if(allowedDir != trainDir)
{
try
{
wait();
}
catch (Exception e)
{
System.out.println(e);
}
}
else
{
System.out.println("Train " + id + " entered track, going " + trainDir);
}
}
// Tells us train has left the track and changes the direction
public synchronized void exitTrack(TrainDirection trainDir, int id)
{
System.out.println(" Train " + id + " left track, going " + trainDir);
allowedDir = (allowedDir == DOWN)? UP : DOWN;
notifyAll();
}
public boolean unsafeToEnter(TrainDirection trainDir)
{
return false; //always safe!?
}
}
Thanks