user3516525 user3516525 - 6 months ago 20
Java Question

Changed the element of a LinkedList - Need to change the rest

My program is a train schedule showing cities and arrival and departure times.
In the program you can type "Delay" and then type the city name and #ofminutes to add a delay in minutes to that cities arrival time. This information is all stored in a LinkedList

Station Arrival Departure Day
Vancouver ----- 20:30 1
Kamloops 06:00 06:35 2
Jasper 16:00 17:30 2
Edmonton 23:00 23:59 2
Saskatoon 08:00 08:25 3
Winnipeg 20:45 22:30 3


My output starts off like this ^^^

So in my 'delay' method I am able to bring up the city specified and add the minutes to the arrival time and everything works great. Code for this is below:

public void delay(String station,int minute){
String cityDelay=station;
int timeDelay=minute;
for(Station list: schedule){
if (cityDelay.equalsIgnoreCase(list.getCity())){
Calendar c = list.getArrivalDate();
c.add(Calendar.MINUTE, timeDelay);
System.out.println(list.getArrival()); //to see if it updated
}
}
}


However, it is this point where I have to add those same minutes to the rest of the times on the list but not have it apply those changes to cities before the delay was implemented.

For example, if I type in "Edmonton" and "30", the output should look like this:

Station Arrival Departure Day
Vancouver ----- 20:30 1
Kamloops 06:00 06:35 2
Jasper 16:00 17:30 2
Edmonton 23:30 00:29 2
Saskatoon 08:30 08:55 3
Winnipeg 21:15 23:00 3


(I will figure out how to update the day after I get times working)

I have no idea how to loop through this and apply the update of minutes to the remainder of the list while excluding the elements prior to the selected city. Any looping ideas I can think of would just go through the entire list.
Thoughts? Concepts I should look up/google?
Thanks in advance.

Answer

You can use the following modified code to update the arrival times of the cities/stations coming after the city/station for which the delay was added:

public void delay(String station,int minute){
String cityDelay=station;
int timeDelay=minute;
boolean updateRest = false;
for(Station list: schedule){
    if (cityDelay.equalsIgnoreCase(list.getCity())){                    
        updateRest = true;          
    }
    if(updateRest){
        Calendar c = list.getArrivalDate();                 
        c.add(Calendar.MINUTE, timeDelay);              
        System.out.println("City: "+list.getCity()+"Updated Arrival time: "+ list.getArrival());  //to see if it updated   
    }
}
updateRest = false;
}

You can also insert the logic to update the day in the if(updateRest) block if you want to change that too. Hope this helps.

Comments