当前位置: 首页 > 知识库问答 >
问题:

使用递归返回最小值和最大值及其在arraylist中的位置

姜森
2023-03-14

我需要编写一个递归函数,返回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;
}

共有1个答案

方坚壁
2023-03-14
public void getMinMax(MinMaxObject minMaxObject, List list, int currentIndex)
{

if(list.get(currentIndex) < minMaxObject.getMin())

    minMaxObject.setMin(list.get(currentIndex) );
    minMaxObject.setMinPos(currentIndex) ;

else if(list.get(currentIndex) > minMaxObject.getMax())

    minMaxObject.setMax(list.get(currentIndex));
    minMaxObject.setMaxPos(currentIndex) ;

if(currentIndex < list.size-1) getMinMax(minMaxObject, list, ++currentIndex)

}
 类似资料: