Dart False首次运行正常,但是如果我再次运行代码并以真实的方式开始,即使我输入false
问候!当我运行此代码并输入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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在定义两个不同的变量,称为
用户名
,其中第一个是在main()
方法中定义的,而另一个位于while
方法代码>循环。访问变量时,DART将从您所处的范围中搜索它,然后将搜索扩展到外部范围,如果它找不到变量。但是
使用的表达式
在确定循环时应继续,无法访问循环中定义的范围。因此,它看到了第一个用户名
main()
中定义的变量。因此,问题在于,当您使用
var
时,您告诉DART,它应该定义一个新变量而不是使用现有变量。因此,代替:
您应该只执行以下操作以参考称为
用户名
的现有变量:You are defining two different variables called
userName
where the first are defined inside themain()
method while the other are inside the scope of thewhile()
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 firstuserName
variable defined inmain()
.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:
You should just do the following to refer to the existing variable called
userName
: