简体   繁体   English

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

[英]I am having trouble calling upon a static recursive method in Java

I am trying to add up the elements in an array all while using a recursive method. 我正在尝试使用递归方法将所有元素加到数组中。 However, I can't execute the method since I get an error. 但是,由于出现错误,我无法执行该方法。 So, since I am using parameters in the static method, is there a way to execute it based on my code? 因此,由于我在静态方法中使用参数,是否有一种方法可以基于我的代码执行它?

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;
        }
    }
}

Change this line 更改此行

summation(array[], b);

to

summation(array, b);

[] denotes array type, you only need the identifier. []表示数组类型,只需要标识符。

  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);
  }

Compile error was on that summation call. 该求和调用出现编译错误。 Your code now compiles but still have some runtimes errors 您的代码现在可以编译,但是仍然存在一些运行时错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM