我正在尝试编写一个简单的递归程序,它将打印出输入之前的所有整数和输入本身的规范和。例如,输入 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/