我需要编写一个递归函数,返回 ArrayList 中最大和最小的元素以及相应的索引。要返回这四项,我需要返回一个对象,该对象是名为 MinMaxObject 的内部类的一个实例,它具有四个已定义的私有(private)变量:max、min、maxPos、minPos,类型为 double、double、int 和 int。
我自己来到这里,我需要开始递归,但我不知道如何开始。如果有人能给我指出正确的方向,我应该能够接受它。
public static void main(String args[]) {
Scanner console = new Scanner(System.in);
System.out.print("Please enter a file name");
String fileName = console.next();
try {
File fileRef = new File(fileName);
Scanner tokens = new Scanner(fileRef);
double input = tokens.nextDouble();
ArrayList<Double> list = new ArrayList<Double>();
while (tokens.hasNextLine()) {
list.add(input);
}
System.out.println("For Loop");
for (int counter = 0; counter < list.size(); counter++) {
System.out.println(list.get(counter));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 2 functions, one initialize & one to call the original recursion
//can start at beggining and recurse to the end or vice versa
//updates the min and max as it goes
//update minPos and maxPos as well
}
public class MinMaxObject {
private double min;
private double max;
private int minPos;
private int maxPos;
public MinMaxObject(double newMin, double newMax, int newMinPos, int newMaxPos){
min = newMin;
max = newMax;
minPos = newMinPos;
maxPos = newMaxPos;
}
public double getMin(){
return min;
}
public void setMin(double newMin){
min = newMin;
}
public double getMax(){
return max;
}
public void setMax(double newMax){
max = newMax;
}
public int getMinPos(){
return minPos;
}
public void setMinPos(int newMinPos){
minPos = newMinPos;
}
public int getMaxPos(){
return maxPos;
}
public void setMaxPos(int newMaxPos){
maxPos = newMaxPos;
}
最佳答案
听起来递归是作业的一部分。
最简单的方法是遍历 arraylist,但由于您需要递归,所以它有点复杂。因为这是家庭作业,而且因为我很懒,所以我不会给你可编译的 Java 代码。这是一个近似值。我也不打算给你整个方法,因为你应该从这里弄清楚剩下的部分。
private int min = 0;
private int max = 0;
findMinMax(int index, List<int> list)
{
//in recursion always start your method with a base-case
if(index >= list.Count)
return ;
//find min and max here
//this is called tail recursion, it's basically the same as a loop
findMinMax(index + 1, list);
}
关于java - 使用递归返回最小值和最大值及其在数组列表中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471548/