重复switch语句直到有效

问题描述 投票:0回答:1
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");
  }
}
loops dart if-statement switch-statement
1个回答
1
投票

要重复事情,你需要一个循环。

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
,因为您期望结果可为空)。

© www.soinside.com 2019 - 2024. All rights reserved.