如果我有三个名为car的对象数组,并说该类具有以下实例变量:
这是我的主数组的样子:
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;
}
}
}
答案 0 :(得分:0)
因为您需要迭代3个数组,并且如果3个Car
数组的大小相同,for loop
比for 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();