有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java转换为递归方法

我是递归新手,有人能给我点化一下吗

问题是:

Find the average grade of the quiz of the Students with #101."

我已经用迭代法解决了它,但我不知道如何将它转换成递归

import java.io.*; 
import java.util.*;

public class Test{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Scanner sc = new Scanner(System.in);

        String arr[][] = {{"101","Quiz","90"},{"101","CS","80"},{"102","Quiz","85"},{"101","Quiz","75"},{"103","CS","84"},{"101","Quiz","87"}};
        int sum = 0;
        int ave = 0;
        System.out.println("Student #\tType\tGrade");
        for(int ctr = 0; ctr<arr.length; ctr++){
            System.out.println(arr[ctr][0]+"\t\t"+arr[ctr][1]+"\t"+arr[ctr][2]);

            if(arr[ctr][0] == "101"){
                if(arr[ctr][1] == "Quiz"){
                    sum += Integer.parseInt(arr[ctr][2]);
                    ave += 1;
                }
            }

        }
        System.out.println("The Average quiz of Student # 101 is: "+ sum/ave);


    }



}

共 (1) 个答案

  1. # 1 楼答案

    你可以这样做,但我不认为这是优雅/实用/良好的做法:

    public int[] recursiveAverage(String array[][], int i){
        if (i < array.length)
        {
            int[] previousAverage = recursiveAverage(array, i + 1);
        }
        else
        {
            int[] previousAverage = {0, 0};
        }
    
        if (array[i][0] == "101" && array[i][1] == "Quiz")
        {
            previousAverage[0] = Integer.parseInt(array[i][2]);
            ++previousAverage[1];
        }
    
        return previousAverage;
    }
    

    然后用previousAverage[0]除以previousAverage[1]得到实际平均值。 这实际上是您的迭代函数,用递归替换for循环

    要有创意