【发布时间】:2021-09-11 07:13:49
【问题描述】:
我正在尝试创建一个简单的递归函数,它生成一个介于 0 和 4 之间的随机数,并且这个生成的数字不应该等于 'correctIndex'。
random(min, max) {
var rn = new Random();
int ans = 0;
ans = (min + rn.nextInt(max - min));
if (ans == correctIndex) {
print("Recursive $ans $correctIndex");
random(0, 4);
} else {
print("Correct Index $correctIndex 5050 $ans");
return ans;
}
}
我调用上面的函数如下:
setState(() {
randomIndex = random(0, 4);
});
print("output value of $randomIndex");
递归部分不被称为“randomIndex”的时间有一个值。但是无论何时调用递归部分,即使函数返回一个值,randomIndex 的值也为 null。以下是调用递归时调试控制台的输出
I/flutter ( 5071): Recursive 2 2
I/flutter ( 5071): Correct Index 2 5050 3
I/flutter ( 5071): output value of null
如果没有调用递归,以下是输出:
I/flutter ( 5071): Correct Index 2 5050 1
I/flutter ( 5071): output value of 1
有人可以指导我了解我做错了什么。提前谢谢你。
【问题讨论】:
-
请注意,如果您为函数声明了返回类型,您的错误就会被捕获。 (您还应该为参数声明类型。)类型系统可以帮助捕捉错误。