【发布时间】:2022-11-01 23:10:24
【问题描述】:
所以我有一个包含 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]);
}
}
【问题讨论】:
标签: java arrays object inheritance polymorphism