dart 重复switch语句直到它有效

fdx2calv  于 2023-10-13  发布在  其他
关注(0)|答案(1)|浏览(117)
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");
  }
}
qgelzfjb

qgelzfjb1#

为了重复,你需要一个循环。
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");
  }
}

(You可能意味着使用int.tryParse而不是int.parse,因为您希望得到可空的结果)。

相关问题