【问题标题】:Dart - Recursive function returning nullDart - 返回 null 的递归函数
【发布时间】: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

有人可以指导我了解我做错了什么。提前谢谢你。

【问题讨论】:

  • 请注意,如果您为函数声明了返回类型,您的错误就会被捕获。 (您还应该为参数声明类型。)类型系统可以帮助捕捉错误。

标签: flutter dart recursion


【解决方案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)?

【讨论】:

  • 添加 return random(0,4) 解决了这个问题。谢谢
猜你喜欢
  • 2019-05-30
  • 2022-06-29
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多