【问题标题】:I am trying to write a recursive function that will return the result of the sum (integer) and takes one argument我正在尝试编写一个递归函数,它将返回总和(整数)的结果并接受一个参数
【发布时间】:2020-06-04 01:38:10
【问题描述】:

我正在尝试遵循以下说明: 编写一个程序,询问用户整数 n 的值,并计算总和 1 + 2 + 3 + 4 + ... + n。本实验的要求是编写一个递归函数,该函数返回总和(整数)的结果,并接受一个整数类型的参数 n。然后您将调用该函数并打印出它的结果,如下所示:

int mysum = recursive_addition(n);

System.out.println("1+2+...+n的和为:"+ mysum);

问题出在第20行,因为下面的错误

Main.java:20: error: method main (String[]) Is already defined in class Main
    private static void main (String args[])
                        ^

这是我的代码:

import java.util.Scanner;
public class Main {
  public static void main(String[] args){
    Scanner s = new Scanner(System.in);
    System.out.print("Please enter a integer: ");
    int n = s.nextInt();
    int mysum = recurSum(n);
    System.out.println("The sum 1+2+3+4 is  :" + n );

    }

    public static int recurSum(int n) 
    { 
        if (n <= 0) 
            return n; 
        return n + recurSum(n - 1); 
    } 

    public static void main (String args[]) 
    { 
        int n = 5; 
        System.out.println(recurSum(n)); 
    } 
} 

【问题讨论】:

  • 您已经定义了方法 'public static void main(String[] args)' 两次,一次作为第一个方法,然后再次作为最后一个方法。正如您的错误所述,您不允许这样做。删除最后一个。

标签: java


【解决方案1】:

正如编译器所说,您正在复制应用程序的主要入口点。

去掉最后一个main函数,修改如下

这是工作代码

import java.util.Scanner;
public class Main {
  public static void main(String[] args){
    Scanner s = new Scanner(System.in);
    System.out.print("Please enter a integer: ");
    int n = 5; // Just put there the number
    int mysum = recurSum(n);
    System.out.println("The sum 1+2+3+4 is  :" + n );

    }

    public static int recurSum(int n) 
    { 
        if (n <= 0) 
            return n; 
        return n + recurSum(n - 1); 
    } 

} 

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2021-08-19
    • 1970-01-01
    • 2017-02-03
    • 2013-09-16
    相关资源
    最近更新 更多