class Generate // to print all numbers from 1000 to 9999 whose digits are in ascending order
{
private boolean order(int n, int i) // checks if the digits of given number are in ascending order
{
if (n == 0) return true;
if (n % 10 < i) return (order(n / 10, n % 10));
return false;
}
void show(int n) // recursive function to generate numbers from 1000 to 9999
{
if (n > 9999) // base case for recursor
System.out.print("");
else
{
if (order(n, 10)) // if digits are in ascending order, prints the number
System.out.println(n);
show(n + 1); // recursive call
}
}
}
上面的代码应该打印1000到9999之间的所有数字。编译和运行的代码,但收到一个运行时异常:java.lang.StackOverflowError: null
。试捕块能解决我的问题吗?这是我第一次在这里发帖,所以我不熟悉问题的礼仪,如果我错了,请纠正我。
发布于 2022-11-13 05:17:17
Java (和大多数编程语言)提供了用于堆栈帧的有限数量的内存槽,当程序/代码达到这个限制时,就会抛出StackOverFlow错误。
在您的情况下,您的程序在到达基本条件之前就达到了这个极限。
我对这个的看法-
发布于 2022-11-13 08:05:42
在我看来,StackOverFlow是由双重递归造成的,即显示()和order()都是递归的。我认为show()不需要是递归的。修改代码如下:
public static void main(String[] args) {
/
new Generate().show(); // added main function to get output or exception.. you can omit it and call Generate().show() at the point u require.
}
}
class Generate//to print all numbers from 1000 to 9999 whose digits are in ascending order
{
private boolean order(int n, int i)//checks if the digits of given number are in ascending order
{
if(n==0)
return true;
if(n%10<i)
return(order(n/10,n%10));
return false;
}
void show()//function to generate numbers from 1000 to 9999 - WITHOUT Recursion
{
int n = 1000;
while(n<=9999)
{ if(order(n,10))//if digits are in ascending order, prints the number
System.out.println(n);
n++;
}
}
}
这是输出:(仅显示前7次迭代) 1234 1235 1236 1237 1238 1239 1245 .
https://stackoverflow.com/questions/74418579
复制相似问题