jon carver jon carver - 7 months ago 12
Java Question

JAVA method to return total number of people picked up in a bus route

So this is my class "Stop" where i have a variable of type "station" (that class is not relevant for this matter) and an int variable "nPeople" that stands for the number of people that are going in the bus in that station:

public class Stop {

private Station station;
private int nPeople;


public Stop(Station station, int nPeople) {
this.station = station;
this.nPeople = nPeople;
}


public Station getStation() {
return station;
}
public void setStation(Station station) {
this.station = station;
}

public int getnPeople() {
return nPeople;
}
public void setnPeople(int nPeople) {
this.nPeople = nPeople;
}
}


And now this is my class "Route" where i have an array variable of the type "Stop" that stores all the stops that the bus does making it a bus route and i want a method "getTotalPeople" that returns the total number of people that the bus picked up in a route:

public class Route {


private Station start;
private Stop[] stops;

public Route(Station start, Stop[] stops) {
this.start = start;
this.stops = stops;
}

public Station getStart() {
return start;
}

public void setStart(Station start) {
this.start = start;
}

public Stop[] getStops() {
return stops;
}

public void setStops(Stop[] stops) {
this.stops = stops;
}



public int getTotalPeople(){

}

}


Any ideas how to return the summation of "nPeople" variable of the "Stop[] stops" array?

Answer
public int getTotalPeople(){
  int total = 0;
  for(int i =0; i < stops.length ; i++){
       total += stops[i].getnPeople();
  }
  return total;
}