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循环有关,并尝试了很多方法来修复它,但想不出更好的方法。
答案 0 :(得分:1)
负责终止递归的ackermann
方法的基本情况不处理小于零的数字,所以你会无限地进入else子句,或者直到你的堆栈用完为止,以先到者为准....
public static int ackermann(int m, int n) {
if(m == 0) <--nope
return n + 1;
if(n == 0) <--nope
return ackermann(m - 1, 1);
else
return ackermann(m - 1, ackermann(m, n - 1)); <-- here we go again
}
我不记得ackermann
函数的精确定义,但是当m&lt;时,你很容易阻止StackOverflowError
。 0用:
public static int ackermann(int m, int n) {
if(m <= 0)
return n + 1;
if(n == 0)
return ackermann(m - 1, 1);
else
return ackermann(m - 1, ackermann(m, n - 1));
}
答案 1 :(得分:0)