入力と入力自体の前にあるすべての整数の標準的な合計を出力する単純な再帰プログラムを作成しようとしています。たとえば、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の入力で、現在取得しています:「5 + 44 + 33 + 22 + 11Exception in thread "main" java.lang.StackOverflowError...」