所以我有一個包含 15 個飛行物件的陣列,flyingObjects 類由 1 個變數(價格:雙)及其 getter 和 setter 組成。我還有一個擴展 FlyingObjects 的飛機類,一個擴展 Airplane 的直升機類,以及擴展直升機的四旋翼和多旋翼類。在樹的另一邊,我有一個擴展 FlyingObjects 的 UAV 類、一個擴展 UAV 的 MAV 類和一個擴展 UAV 的 AD 類。
這是陣列:
FlyingObjects [] test = new FlyingObjects[7];
test[0] = new Uav(10,43);
test[1] = new AgriculturalDrone(8000,780000,"Chase",2400);
test[2] = new Uav(10,5);
test[3] = new Mav(0.5,140000,"trooper",10);
test[4] = new Multirotor("Hexa",140000,200,185,2021,1,4);
test[5] = new Helicopter("Robinson",199000,250,100,2018,7);
test[6] = new Airplane("Boeing",350000,450);
現在我需要撰寫一個方法來獲得陣列中最昂貴和最便宜的無人機(請注意,價格始終是無人機建構式中的第二個屬性)。出于某種原因,我的方法總是將陣列中的第一個無人機作為最便宜的無人機回傳,而將陣列中的最后一個無人機作為最昂貴的無人機回傳。有關如何解決此問題的任何提示?
public static void findLeastAndMostExpensiveUAV(FlyingObjects[] flyingObjects) {
int mostExpensive = -1;
int leastExpensive =1000000000;
boolean hasUav = false;
if(flyingObjects == null) {
System.out.println("There is no UAV");
}
for(int i = 0;i<flyingObjects.length;i ) {
if (flyingObjects[i] instanceof Uav) {
Uav a = (Uav) flyingObjects[i];
if (a.getPrice() >= mostExpensive) {
mostExpensive = i;
}if (a.getPrice() <= leastExpensive){
leastExpensive = i;
}
if(!hasUav) {
hasUav = true;
}
}
}
if(!hasUav) {
System.out.println("There is no UAV");
}
else {
System.out.println("\nInformation about the most expensive UAV: \n" flyingObjects[mostExpensive] "\n");
System.out.println("Information about the least expensive UAV: \n" flyingObjects[leastExpensive]);
}
}
uj5u.com熱心網友回復:
您的mostExpensive和leastExpensive變數似乎代表Uav陣列中最高和最低價格物件的索引以及所有Uav物件的最高和最低價格的價格。
您應該分別跟蹤最小/最大價格(型別)和最小/最大定價物件(型別)double的索引,可能在如下所示的變數中:Uavint
int maxPricedUavIndex;
int minPricedUavIndex;
double maxPrice = 0d;
double minPrice = Double.MAX_VALUE;
您將在適當的情況下將maxPricedUavIndex和分配給minPricedUavIndex索引的值i,并且您將在適當的情況下將maxPrice和分配minPrice給a.getPrice()
uj5u.com熱心網友回復:
使用 StreamAPI 的另一種方式:
var stat = Arrays.stream(flyingObjects)
.filter(o -> o instanceof UAV)
.collect(Collectors.teeing(
Collectors.minBy(Comparator.comparingDouble(FlyingObject::getPrice)),
Collectors.maxBy(Comparator.comparingDouble(FlyingObject::getPrice)),
(min, max) -> new MinMaxStatistic<>(min.orElse(null), max.orElse(null))));
FlyingObject min = stat.min;
FlyingObject max = stat.max;
你需要一個類來收集統計資料
class MinMaxStatistic<T> {
T min;
T max;
public MinMaxStatistic(T min, T max) {
this.min = min;
this.max = max;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524731.html
標籤:爪哇数组目的遗产多态性
