java - 如何修复我的简单 Java 递归方法?

标签 java recursion stack-overflow

我正在尝试编写一个简单的递归程序,它将打印出输入之前的所有整数和输入本身的规范和。例如,输入 5 应打印出“1 + 2 + 3 + 4 + 5”。输入必须大于零。如果能朝正确的方向前进,我们将不胜感激。

import java.util.Scanner;

public class Quiz10 
{
    public static void main (String[] args)
    {
        int input;
        System.out.println("Please enter an integer greater than one: ");
        Scanner scan = new Scanner(System.in);
        input = scan.nextInt();
        sumReverse(input);
    }
    public static void sumReverse(int n)
    {
        int x = n;

        if(x == 1)
            System.out.print(x);
        else if(x > 0)
        {
            System.out.print(x + " + " + (x-1));
        }
        x--;
        sumReverse(x);
    }
}

编辑:输入 5 我当前得到:“线程“main”java.lang.StackOverflowError 中的 5 + 44 + 33 + 22 + 11Exception...”

最佳答案

您缺少终止条件。试试这个:

public static void sumReverse(int n)
{
    if(n == 1) {
        System.out.print(n);
        return;
    }
    else if(n > 0)
    {
        System.out.print(n + " + " + (n-1));
    } else return;
    sumReverse(--n);
}

一旦 n 达到 1 或 1 小于或等于 0,此函数将停止。

另一种选择是:

public static void sumReverse(int n)
{
    if(n == 1) System.out.print(n);
    else if(n > 0)
    {
        System.out.print(n + " + " + (n-1));
        sumReverse(--n);
    }        
}

这具有相同的效果。

关于java - 如何修复我的简单 Java 递归方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15727754/

相关文章:

java - 从另一个类引用 MainActivity 中的 RadioButton 时出错

java.lang.UnsatisfiedLinkError : org. opencv.core.Core

java - 如何将 Vector 的内容转储到新文件中?

java正则表达式匹配字符串,其中包含没有数字的单词,并且可以选择用逗号分隔

Java 堆栈溢出错误 - 如何在 Eclipse 中增加堆栈大小?

asp.net - 调用 DataContext.SubmitChanges() 时出现 StackOverflow 错误

java - 在位于 onViewCreated() 外部的 Runnable 内部使用 Glide

recursion - 如何在 clojure 中调用 2 个连续函数?

javascript - 如何在动态生成的 HTML 表中停止递归

recursion - 迭代还是递归来实现二叉搜索树?