import 'dart:io';
//Week days
enum WeekDays {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}
void main() {
print("Enter the number from 1-7");
int? WeekDayNumber = int.parse(stdin.readLineSync()!);
switch (WeekDayNumber) {
case 1:
print("Monday");
break;
case 2:
print("Tuesday");
break;
case 3:
print("Wednesday");
break;
case 4:
print("Thursday");
break;
case 5:
print("Friday");
break;
case 6:
print('Saturday');
break;
case 7:
print('Sunday');
break;
default:
print("Please re-enter your number");
}
}
要重复事情,你需要一个循环。
Dart 具有三个循环结构,
for
(实际上是两个:for(;;)
和 for( in )
)、while(){}
和 do{}while();
您可以使用循环条件并将其设置为在找到好的答案时退出循环,或者您可以只使用始终为真的条件并使用
break
退出。
在这种情况下,您总是希望至少运行一次,因此我将使用
do
/while
和条件变量:
bool success = false;
do {
print("Enter the number from 1-7");
int? WeekDayNumber = int.tryParse(stdin.readLineSync()!);
switch (WeekDayNumber) {
case 1:
print("Monday");
success = true; // <-- sets loop condition on success.
break;
// ...
default:
print("Please re-enter your number");
}
} while (!success);
如果使用break,在不使用条件的情况下,我会使用
while (true)
作为规范的“永远循环”。其他语言喜欢 for(;;)
,但 Dart 用户似乎更喜欢 while (true)
,可能是因为它读起来更好:
loop: // <- label for the loop, so you can break it from inside switch.
while (true) {
print("Enter the number from 1-7");
int? WeekDayNumber = int.tryParse(stdin.readLineSync()!);
switch (WeekDayNumber) {
case 1:
print("Monday");
break loop; // <-- exits loop directly on success.
// ...
default:
print("Please re-enter your number");
}
} while (!success);
(您可能打算使用
int.tryParse
而不是 int.parse
,因为您期望结果可为空)。