flutter - Dart - 返回 null 的递归函数
问题描述
我正在尝试创建一个简单的递归函数,它生成一个介于 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
有人可以指导我做错什么。先感谢您。
解决方案
这段代码相当于:
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;
}
return null; // <-- NOTE! dart (flutter) will auto do this.
}
因此,当if
为真时,您最终将返回 null!
所以也许你想random(0, 4);
成为return random(0,4)
?
推荐阅读
- typescript - 当我只有 TurnContext 时,如何在 Microsoft Bot Framework v4 中获取调用者的 TenantID?
- node.js - Heroku 部署因非必需节点模块而崩溃
- c++ - 如何防止双精度值到整数的隐式转换
- python - 导入模块类型错误
- c# - 我没有从数据库中获取任何数据
- javascript - 刺激点击按钮。问题
- javascript - 基于行和列将 JSON 导出为 CSV
- javascript - 标识符‘setValues’已经被声明”
- javascript - 如何在向 Spring API 发送查询方向的 javascript 中格式化 Pageable json 对象
- python - 使用 Python 从字母数字文本中分离文本和数字