[英]This code runs infinitely, and I'm clueless on why it isn't working
public class Main1
{
public static void main(String[] args)
{
printNumbers(7, 3);
}
public static int printNumbers(int numValue, int rows) {
for (int i = 0; i < rows; i++) {
int x = (int)(Math.random() * 10);
System.out.print(x);
if (numValue == x && i < rows) {
System.out.println(" ");
} else if (i < rows) {
System.out.print(x);
}
}
return printNumbers(7, 3);
}
}
It's supposed to print random numbers until you reach the numValue, then it creates a new row, and there is a specified amount of rows.它应该打印随机数,直到达到 numValue,然后它会创建一个新行,并且有指定数量的行。 Although I put 3 rows, this code keeps running infinite rows.
虽然我放了 3 行,但这段代码一直在运行无限行。 I must be missing something.
我肯定错过了什么。 I'm new to making methods and this is my first crack at it all by myself.
我是制作方法的新手,这是我自己第一次尝试。
This method would recourse endlessly, as it unconditionally calls printNumbers(7,3)
when it returns.此方法将无休止地求助,因为它在返回时无条件调用
printNumbers(7,3)
。 From the looks of it, it doesn't seem you even need a return value there - change the return type to void
, drop the return
statement and you should be OK:从外观上看,您似乎甚至不需要返回值 - 将返回类型更改为
void
,删除return
语句,您应该没问题:
public static void printNumbers(int numValue, int rows){
for (int i = 0; i < rows; i++) {
int x = (int)(Math.random() * 10);
System.out.print(x);
if (numValue == x && i < rows) {
System.out.println(" ");
} else if (i < rows) {
System.out.print(x);
}
}
}
Every recursive method should have a termination condition.每个递归方法都应该有一个终止条件。 I updated the same program to work correctly and it terminates the program when random numbers reach to numValue
我更新了相同的程序以正常工作,并在随机数达到 numValue 时终止程序
public static void main(String[] args) {
printNumbers(7, 3);
}
public static void printNumbers(int numValue, int rows) {
for (int i = 0; i < rows; i++) {
int x = (int) (Math.random() * 10);
System.out.print(x);
if (numValue == x && i < rows) {
System.out.println(" ");
return;
} else if (i < rows) {
System.out.print(x);
}
}
printNumbers(7, 3);
}
//OUTPUT: 66003311997 //输出:66003311997
There is no break/terminate condition in your recursion logic, this is causing your loop to run indefinitely.递归逻辑中没有中断/终止条件,这会导致循环无限期地运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.