import java.util.Scanner;
//create AckermannsFunction class
public class Ackermann
{
public static void main(String[] args) {
//instance variables
String input; //holds user input for the numbers
int num1; //holds first number
int num2; //holds second number
//create new Scanner
Scanner keyboard = new Scanner(System.in);
do {
//get first number from user
System.out.println("Enter a number: ");
input = keyboard.nextLine();
num1 = Integer.parseInt(input);
//get second number from user
System.out.println("Enter another number: ");
input = keyboard.nextLine();
num2 = Integer.parseInt(input);
System.out.println("Result: \n Ackermann: (" + num1 + "," + num2 + ") = " + ackermann(num1, num2));
}
//while(Integer.parseInt(input) != -1);
while(num1 != -1 || num2 != -1);
System.out.println("Bye!");
}
public static int ackermann(int m, int n) {
//calculate if m = 0
if(m == 0)
return n + 1;
if(n == 0)
return ackermann(m - 1, 1);
else
return ackermann(m - 1, ackermann(m, n - 1));
}
}
这是我不断收到的错误:
Exception in thread "main" java.lang.StackOverflowError
at Ackermann.ackermann(Ackermann.java:44)
每当我为第一个数字输入 -1 为第二个数字输入 -1 时,这种情况就会发生很多次。我知道它与 while 循环有关,并且尝试了很多方法来修复它,但想不出更好的方法来解决它。