对于类项目,我必须使用递归方法返回一个数组中具有最大权值的对象。我无法为我的生活获得正确的输出。该方法返回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;
}
}
任何帮助或指导将不胜感激。 谢谢!
你'else'块完全忽略了递归调用的返回 - 所以返回的'max'将始终保持一个第一呼叫分配(这是你通过的索引) – UnholySheep
@Os。“n”是列表的长度。我认为这是问题,但我不知道如何跟踪最大长度的数据包并将其返回。根据项目限制,我无法实例化任何Packet对象以跟踪maxWeightPacket方法的外部。 – JMarotta
@JMarotta你可以在你的问题中包含方法签名不能改变,因为这是事实。 –