因此,这是我的“ Stop”类,其中有一个类型为“ station”的变量(该类与该问题无关)和一个int变量“ nPeople”代表那次乘公交车的人数站:

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;
    }
}


现在这是我的“ Route”类,其中有一个类型为“ Stop”的数组变量,该变量存储公交车将其转为公交车路线的所有停靠站,我想要一个方法“ getTotalPeople”来返回总人数公交车在一条路线上上车:

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(){

    }

}


有什么想法如何返回“ Stop [] stops”数组的“ nPeople”变量的总和?

最佳答案

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

07-25 23:58