简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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