返回带有Max元素的对象的Java递归
对于类项目,我必须使用递归方法返回数组中权重最大的对象。我一生都无法获得正确的输出。在我的主方法中调用该方法时,该方法在传递的确切索引处返回数据包对象。这是我为该方法编写的代码返回带有Max元素的对象的Java递归,java,arrays,object,recursion,Java,Arrays,Object,Recursion,对于类项目,我必须使用递归方法返回数组中权重最大的对象。我一生都无法获得正确的输出。在我的主方法中调用该方法时,该方法在传递的确切索引处返回数据包对象。这是我为该方法编写的代码 public Packet maxWeightPacket(Packet[] list, int n) { Packet max = new Packet(0, 0.00, ""); if (n == 0) { return list[n]; } else { if
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;
}
}
任何帮助或指导都将不胜感激。
谢谢 由于您无法更改方法的签名,您可以做的是:
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]中的最大权重
Packet max=new Packet(0,0.00,”)代码>似乎是问题所在
您正在每个递归调用中定义新的max数据包
您应该做的是在maxweightpack
方法之外定义packetmax
将代码更改为以下内容:
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,0.00,”);
公共静态数据包maxWeightPacket(数据包[]列表,int n){
if(n<0){
返回最大值;
}否则{
如果(列表[n].getWeight()>最大getWeight()){
max=列表[n];
}
maxWeightPacket(列表,n-1);
}
返回最大值;
}
yourelse
块完全忽略递归调用的返回-因此返回的max
将始终保持在第一次调用中分配的调用(这是您传入的索引)@Os。“n”是列表的长度。我认为这就是问题所在,但我不知道如何跟踪最大长度的数据包并将其返回。根据项目限制,我无法实例化任何数据包对象来跟踪maxWeightPacket方法之外的数据包对象。@JMarotta您能否在问题中包括方法签名不能更改,因为情况就是这样。项目受到限制,因此我无法在类递归中定义任何其他数据包对象,其中maxWeightPacket方法是。所有操作都必须在该方法内完成。您可以更改方法签名吗?不幸的是,不能。方法签名必须是:public Packet maxweightpack(Packet[],int n),那么除了maxweightpack
方法内,您可以更改代码的哪一部分?你能添加另一种方法吗?就我个人而言,我认为仅仅因为你有限制而无法实现,就给出一个否定是不好的。如果你能编辑代码,答案就行了。不幸的是,我不能通过添加任何附加参数来更改方法签名。请检查新的解决方案@JMarotta