Dart False首次运行正常,但是如果我再次运行代码并以真实的方式开始,即使我输入false

发布于 2025-02-13 16:50:43 字数 453 浏览 2 评论 0原文


问候!当我运行此代码并输入false(Allan)时,代码第一次执行良好,但是如果我再次运行A并输入True(例如John,Eric等),则代码也将成为无限环路,即使我输入在程序中间停止的错误

void main() {
  print('Please enter the user name:');
  var userName = stdin.readLineSync()!;

  while (userName != 'Allan') {
    print('Sorry that is not the correct user name. Please try Again');
    var userName = stdin.readLineSync()!;
  }
  print('Hey $userName welcome');
}

Greetings! when I run this code and enter a false(Allan) the first time the code executes well but if I run it a again and enter a true(eg John,Eric etc) the code, it becomes an infinity loop even if I enter a false in the middle of the program stops

void main() {
  print('Please enter the user name:');
  var userName = stdin.readLineSync()!;

  while (userName != 'Allan') {
    print('Sorry that is not the correct user name. Please try Again');
    var userName = stdin.readLineSync()!;
  }
  print('Hey $userName welcome');
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

扛刀软妹 2025-02-20 16:50:43

您正在定义两个不同的变量,称为用户名,其中第一个是在main()方法中定义的,而另一个位于while方法代码>循环。

访问变量时,DART将从您所处的范围中搜索它,然后将搜索扩展到外部范围,如果它找不到变量。但是使用的表达式在确定循环时应继续,无法访问循环中定义的范围。因此,它看到了第一个用户名 main()中定义的变量。

因此,问题在于,当您使用var时,您告诉DART,它应该定义一个新变量而不是使用现有变量。

因此,代替:

    print('Sorry that is not the correct user name. Please try Again');
    var userName = stdin.readLineSync()!;

您应该只执行以下操作以参考称为用户名的现有变量:

    print('Sorry that is not the correct user name. Please try Again');
    userName = stdin.readLineSync()!;

You are defining two different variables called userName where the first are defined inside the main() method while the other are inside the scope of the while() loop.

When accessing a variable, Dart will search for it from the scope where you are and then widen the search to outer scopes if it does not find the variable. But the expression used by while when determining of the loop should continue, cannot access the scope defined inside the loop. So it sees the first userName variable defined in main().

So the problem is that when you use var, you are telling Dart that it should define a new variable instead of using an existing one.

So instead of:

    print('Sorry that is not the correct user name. Please try Again');
    var userName = stdin.readLineSync()!;

You should just do the following to refer to the existing variable called userName:

    print('Sorry that is not the correct user name. Please try Again');
    userName = stdin.readLineSync()!;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文