Vòng lặp while và do-while trong Dart
1. While loop
var count = 1;
while (count <= 5) {
print(count);
count++;
}
// Output: 1, 2, 3, 4, 52. Do-while loop
var count = 1;
do {
print(count);
count++;
} while (count <= 5);
// Chạy ít nhất 1 lần
var x = 10;
do {
print(x); // In ra 10
} while (x < 5); // false nhưng vẫn chạy 1 lần3. Infinite loop
var count = 0;
while (true) {
print(count);
count++;
if (count >= 5) break;
}4. Ví dụ thực tế: Menu
import 'dart:io';
void main() {
var choice;
do {
print('''
=== MENU ===
1. Start
2. Settings
3. Exit
Choose:
''');
choice = int.tryParse(stdin.readLineSync() ?? '0') ?? 0;
switch (choice) {
case 1:
print('Starting...');
break;
case 2:
print('Settings...');
break;
case 3:
print('Goodbye!');
break;
default:
print('Invalid choice');
}
} while (choice != 3);
}📝 Tóm tắt
while- Kiểm tra trước khi chạydo-while- Chạy ít nhất 1 lầnwhile (true)- Infinite loop- Dùng
breakđể thoát
Last updated on