简体   繁体   English

java.lang.StackOverflowError? 在java中

[英]java.lang.StackOverflowError? in java

i get this " java.lang.StackOverflowError " when i run the code but the problem come when i put a big number like (7,10) 我在运行代码时收到此“ java.lang.StackOverflowError”,但当我输入大数字(7,10)时问题就来了

this is the code that i write 这是我写的代码

The code for calculate The Ackermann Function 计算阿克曼函数的代码

public static void main(String[] args) {
    int m, n, s;
    Scanner maher = new Scanner(System.in);
    System.out.println(" the code for calculate The Ackermann Function ");
    System.out.println(" Enter first number M");
    m = maher.nextInt();
    System.out.println(" Enter Second number N");
    n = maher.nextInt();
    System.out.println("A(" + m + " , " + n + ") = " + Ack(m, n) + " \n");
}
public static int Ack(int m, int n) {
    if (m == 0) {
        return n + 1;
    }
    if (m != 0 && n == 0) {
        return Ack(m - 1, 1);
    }
    if (m != 0 && n != 0) {
        return Ack(m - 1, Ack(m, n - 1));
    }
    return 0;
    // This code written by Maher Al Shammari 212542270 // KFU
}

I try to change the type to long but the problem doesn't solve ,,,, 我尝试将类型更改为long,但是问题无法解决,,,,,

You have created "endless" or at least "too deep" recursion. 您创建了“无尽”或至少“太深”的递归。 This is the problem here. 这就是这里的问题。

Not to talk of the fact that this function is known to grow very very very quickly. 更不用说这个功能众所周知非常非常快地增长的事实。 So you will need BigInteger for it (not int, not long). 因此,您将需要BigInteger(不是int,不会很长)。 Probably though even BigInteger will not get you too far. 即使BigInteger也不会让您走得太远。

  • Stack overflow means too many nested method calls . 堆栈溢出意味着太多的嵌套方法调用

  • Your logic seems right, its surely due many recursive calls involved. 您的逻辑似乎正确,这肯定是由于涉及到许多递归调用。

  • Anyways, I think you should be happy to see result for ACK(4, 4) . 无论如何,我认为您应该很高兴看到ACK(4,4)的结果

  • ACK(7, 10) - really? ACK(7,10) -真的吗? asking too much... its like calling NQueens(16) :P 问得太多...就像打电话给NQueens(16) :P

You can try manipulating the JVM stack size. 您可以尝试操纵JVM堆栈大小。 I'm not sure that this will help in the end, but if you have a machine with a lot of memory, you can increase both the stack and heap and push the failure out further. 我不确定这是否最终会有所帮助,但是如果您有一台具有大量内存的计算机,则可以增加堆栈和堆,并将故障进一步排除。

The default stack size is 384KB. 默认堆栈大小为384KB。 You manipulate it using the -Xss parameter to the JVM. 您可以使用JVM的-Xss参数对其进行操作。 For example, -Xss512k sets the stack size to 512KB. 例如, -Xss512k将堆栈大小设置为512KB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM