In: Computer Science
Using Java, define a train class and write code to demonstrate its functionality
The train should run between Boston and New York, stopping at different, different station along the way.
Provide output to indicate the train’s current status.
/**************************************Train.java*******************************/
import java.util.LinkedList;
public class Train {
//A Linked list store the stations
private LinkedList<String> stations;
private String currentStation;
private String lastStation;
public Train() {
stations = new
LinkedList<String>();
/*
* modify the station names between
Boston and New York
*/
stations.add("Boston");
stations.add("Staion A");
stations.add("Staion B");
stations.add("Staion C");
stations.add("Staion D");
stations.add("Staion E");
stations.add("New York");
currentStation =
stations.getFirst();//get the first station
lastStation =
stations.getLast();//get the last station
stations.poll();//train start run
from first station
}
public LinkedList<String> getStations()
{
return stations;
}
public String getCurrentStation() {
return currentStation;
}
public String getLastStation() {
return lastStation;
}
public void run() {
if (!stations.isEmpty()) {
currentStation =
stations.poll();
} else {
System.out.println("You have reached at: " + lastStation);
}
}
public static void main(String[] args) {
Train train = new Train();
System.out.println("Train at: "
+ train.getCurrentStation());
System.out.println("Train's last
station: " + train.getLastStation());
train.run();
train.run();
System.out.println("Now train at: " + train.getCurrentStation());
train.run();
train.run();
System.out.println("Now train
at: " + train.getCurrentStation());
train.run();
train.run();
train.run();
System.out.println("Now train at: "
+ train.getCurrentStation());
}
}
/*******************************output*****************/
Train at: Boston
Train's last station: New York
Now train at: Staion B
Now train at: Staion D
You have reached at: New York
Now train at: New York
Please let me know if you have any doubt or modify the answer, Thanks :)