当我从另一个班级使用这些方法时,我遇到了不兼容的类型错误,我应该返回所有汽车的数组,其中给定年份的平均马力在指定的范围内。
这是我从其他类返回arraylist的方法:
public ArrayList<Lamborghini> getCarsFromThisYear(int year){
ArrayList<Lamborghini> fromYear = new ArrayList<Lamborghini>();
for( Lamborghini c : inventory){
if(c.getModelYear() == year){
fromYear.add(c);
}
}
if( fromYear.size() == ZERO){
return new ArrayList<>();
}
return fromYear;
}
public Lamborghini[] getCarsWithHorsepowerRange(double lowHP, double highHP){
int matches = ZERO;
for (Lamborghini c : inventory){
if(c.getHorsepower() >= lowHP && c.getHorsepower() <= highHP){
matches++;
}
}
Lamborghini[] horsepower = new Lamborghini[matches];
int indexInArray = ZERO;
for (Lamborghini c : inventory){
if(c.getHorsepower() >= lowHP && c.getHorsepower() <= highHP){
horsepower[indexInArray] = c;
indexInArray++;
}
}
return horsepower;
}
这就是我正在努力的地方,我在调用时遇到错误: c.getCarsFromThisYear(modelYear)和(c.getCarsWithHorsepowerRange(lowHP,highHP)
public LamborghiniCarLot[] getAllCarLotsWithAverageHorsepowerInRangeForYear(int modelYear, double lowHP, double highHP){
int matches = ZERO;
for(LamborghiniCarLot c : carLots){
if (c.getCarsFromThisYear(modelYear)){
if(c.getCarsWithHorsepowerRange(lowHP, highHP)){
matches++;
}
}
}
LamborghiniCarLot[] search = new LamborghiniCarLot[matches];
int index = ZERO;
for(LamborghiniCarLot c : carLots){
search[index] = c;
index++;
}
}
答案 0 :(得分:1)
以下方法存在许多问题:
public ArrayList<Lamborghini> getCarsFromThisYear(int year){
ArrayList<Lamborghini> fromYear = new ArrayList<Lamborghini>();
for( Lamborghini c : inventory){
if(c.getModelYear() == year){
fromYear.add(c);
}
}
if( fromYear.size() == ZERO){
return new ArrayList<>();
}
return fromYear;
}
List<Lamborghini>
而不是ArrayList<Lamborghini>
ArrayList<>()
声明中将ArrayList<Laborghini>
更改为if
。 以下是我的建议:
public List<Lamborghini> getCarsFromThisYear(int year){
List<Lamborghini> fromYear = new ArrayList<Lamborghini>();
for( Lamborghini c : inventory){
if(c.getModelYear() == year){
fromYear.add(c);
}
}
return fromYear;
}
另一个问题是if (c.getCarsFromThisYear(modelYear))
。该方法返回List<Lamborghini>
但if语句需要boolean
值。