【发布时间】:2019-02-01 01:09:43
【问题描述】:
我需要编写一个递归函数,返回 ArrayList 中的最大和最小元素以及相应的索引。要返回这四个项目,我需要返回一个对象,它是一个名为 MinMaxObject 的内部类的实例,它具有四个已定义的私有变量: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;
}
【问题讨论】: