I'm trying to add multiple stops(a stop has the variables ("Station stop" and int numberLiters" to a route with this loop with their respective number os liters.
private int askStation( ) {
Station po=null;
int id;
consola.println("Id Station?");
id = consola.readInt();
po=station.getStation(id);
if( (po==null)){
consola.println("Unknown Station" );
consola.readLine();
return 0;
}
consola.print( "How many litters ");
int nLiters = consola.readInt();
if (po.checksLiters(nLiters)==false)
consola.println("Invalid Quantity");
else {
//ADD STOP TO THE ROUTE
Stop s=new Stop(po,nLiters);
Route r=new Route(1);
r.addStop(s);
consola.println(r.toString());
}
consola.readLine();
consola.clear();
}
This loop is made ax number of times but it only fills the arrayList one time, i made that consola.println(i.toString());
and a for loop to print the data inside the array and no matter how many times i run this script it only adds the last one i typed. this is my class Route:
public class Route {
private int start;
private arrayList<Stop>stops=new arrayList <Stop>();
public Route(int start) {
this.start = start;
}
public void addStop( Stop s ){
stops.add(s);
}
public ArrayList <Stop> getStops(){
return stops;
}
What am i doing wrong? is is the add method? or the initializing of the objects in the askStation method loop?
Stop s=new Stop(po,nLiters);
Route r=new Route(1);
r.addStop(s);
You are creating a new Route each time and then adding a stop to the new route, so you lose the old stops. To avoid that, make Route a field outside the method instead of doing
Route r = new Route();
Also,
arrayList<Stop>
should be
ArrayList<Stop>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.