我在Java中调用静态递归方法时遇到了麻烦

时间:2012-03-10 02:02:07

标签: java arrays methods recursion

我试图在使用递归方法时将数组中的元素加起来。但是,由于出现错误,我无法执行该方法。所以,既然我在静态方法中使用参数,有没有办法根据我的代码执行它?

import java.util.Scanner;
public class Harro {
    public static void main(String[] args) {
        input();
    }

    private static void input() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Lower bound: ");
        int lower = scanner.nextInt();
        System.out.print("Upper bound: ");
        int upper = scanner.nextInt();
        arrayForm(upper, lower);
    }

    private static void arrayForm(int upper, int lower) {
        int b = 0;
        int a = Math.abs(lower) + Math.abs(upper);
        int array[] = new int[a];
        for (int i = 0; i < array.length; i++) {
            array[i] = lower + i;
        }
        summation(array[], b);
    }

    public static int summation(int array[], int b) {
        if (b > array.length) {
            System.out.println("Cannot continue");
            return 0;
        } else{
            int result = array[b] + summation(array, b + 1);
            System.out.println("recursion call: " + b);
            System.out.println("sum: " + result);
            System.out.println("parameter 1: " + array[b]);
            System.out.println("parameter 2: " + array[b + 1]);
            return result;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

更改此行

summation(array[], b);

summation(array, b);

[]表示数组类型,您只需要标识符。

答案 1 :(得分:0)

  private static void arrayForm(int upper, int lower)
  {
    int b = 0;
        int a = Math.abs(lower) + Math.abs(upper);
    int array[] = new int[a];
        for (int i = 0; i < array.length; i++)
    {
        array[i] = lower + i;
    }
    summation(array, b);
  }

编译错误在该求和调用上。您的代码现在编译但仍有一些运行时错误