2017-03-08 26 views
0

对于类项目,我必须使用递归方法返回一个数组中具有最大权值的对象。我无法为我的生活获得正确的输出。该方法返回Packet对象的确切索引,该方法在我的main方法中调用时传递。这是我对该方法的代码。使用最大元素返回对象的Java递归

public Packet maxWeightPacket(Packet[] list, int n) { 
    Packet max = new Packet(0, 0.00, ""); 
    if (n == 0) { 
     return list[n]; 
    } else { 
     if (list[n].getWeight() > max.getWeight()) { 
      max = list[n]; 
     } 
     maxWeightPacket(list, n - 1); 
    } 
    return max; 
} 

代码包类是在这里:

public class Packet { 
    private int idNumber; 
    private double weight; 
    private String destination; 

    public Packet(int idNumber, double weight, String destination) { 
     this.idNumber = idNumber; 
     this.weight = weight; 
     this.destination = destination; 
    } 

    public boolean isHeavy() { 
     if (weight > 10) 
      return true; 
     else 
      return false; 
    } 

    @Override 
    public String toString() { 
     return idNumber + " " + weight + " " + destination; 
    } 

    public double getWeight() { 
     return weight; 
    } 

    public String getDestination() { 
     return destination; 
    } 

} 

任何帮助或指导将不胜感激。 谢谢!

+0

你'else'块完全忽略了递归调用的返回 - 所以返回的'max'将始终保持一个第一呼叫分配(这是你通过的索引) – UnholySheep

+0

@Os。“n”是列表的长度。我认为这是问题,但我不知道如何跟踪最大长度的数据包并将其返回。根据项目限制,我无法实例化任何Packet对象以跟踪maxWeightPacket方法的外部。 – JMarotta

+0

@JMarotta你可以在你的问题中包含方法签名不能改变,因为这是事实。 –

回答

-1

既然你不能改变method's签名,你可以做的是:

public Packet maxWeightPacket (Packet[] list, int n) 
     { 
     Packet pack = new Packet (0,0.00,""); 
     if (n == 0) 
     { 
      return list[n]; 
     } 
     if (list[n].getWeight() > list[n-1].getWeight()) 
     { 
       pack = list[n-1].getWeight(); 
       list[n-1].getWeight() = list[n].getWeight(); 
       list[n].getWeight() = pack; 
       maxWeightPacket(list, n-1); 
     } 
     } 

所以,你会始终保持最大的重量在列表[N-1],直到最后递归调用

+0

不幸的是,我无法通过添加任何附加参数来更改方法签名。 – JMarotta

+0

检查新解决方案@JMarotta –

-1

Packet max = new Packet (0,0.00,"");似乎是问题所在。

您正在每次递归调用中定义新的最大数据包。

你应该做的是定义Packet max方法maxWeightPacket

更改您的代码如下:

Packet max = new Packet (0,0.00,""); 
public static Packet maxWeightPacket(Packet[] list, int n) { 
    if (n < 0) { 
     return max; 
    } else { 
     if (list[n].getWeight() > max.getWeight()) { 
      max = list[n]; 
     } 
     maxWeightPacket(list, n - 1); 
    } 
    return max; 
} 
+0

项目受到限制,因此我无法在类递归中定义任何其他Packet对象,其中maxWeightPacket方法是。一切都必须在该方法内完成。 – JMarotta

+0

你可以改变方法签名吗? –

+0

不幸的是,没有。方法签名必须是:public Packet maxWeightPacket(Packet [],int n) – JMarotta