对具有相同的特定实例变量的对象[在对象数组内]的实例变量求和

时间:2019-03-16 13:00:31

标签: java arrays oop object

如果我有三个名为car的对象数组,并说该类具有以下实例变量:

  1. 字符串carName;
  2. int numberOfDoors;

这是我的主数组的样子:

 car[] volkswagen2016Array = new car[10];
 car[] volkswagen2017Array = new car[10];
 car[] volkswagen2018Array = new car[10];

如果carName在所有这些数组中相同,如何形成for循环或foreach循环以遍历所有这些数组并求和numberOfDoors变量? 谢谢。

编辑:我尝试过的方法:

for (car a : volkswagen2016Array) {
    if (a == null) {
        break;
    } else {
        String carName = a.getCarName(); // a gettter function inside the class
        if (a.getCarName().equalsIgnoreCase(carName)) {
            doorSum += a.getDoorNum(); //doorSum is an int variable inside main, int doorSum = 0;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

因为您需要迭代3个数组,并且如果3个Car数组的大小相同,for loopfor each

int sum = 0;
for(int i=0; i<volkswagen2016Array.length; i++)  {

      if(volkswagen2016Array[i].getCarName().equals(carName)) {
             sum += volkswagen2016Array[i].getNumberOfDoors();
             }

       if(volkswagen2017Array[i].getCarName().equals(carName)) {
             sum += volkswagen2017Array[i].getNumberOfDoors();
             }

       if(volkswagen2018Array[i].getCarName().equals(carName)) {
             sum += volkswagen2018Array[i].getNumberOfDoors();
             }

   }

使用Java-8流

int sum = IntStream.range(0, volkswagen2016Array.length)
          .map(i->Stream.of(volkswagen2016Array[i],volkswagen2017Array[i],volkswagen2018Array[i])
                  .filter(c->c.getName().equals(carName)).mapToInt(Car::getNumberOfDoors).sum()).sum();