Skip to Content
Kotlin📘 Ngôn ngữ Kotlin🔁 Vòng lặp while

Vòng lặp while và do-while trong Kotlin

🎯 Mục tiêu: Hiểu cách sử dụng while loop khi không biết trước số lần lặp.


💡 Khái niệm

  • while: Kiểm tra điều kiện trước khi thực thi
  • do-while: Thực thi ít nhất 1 lần, rồi mới kiểm tra điều kiện

📝 while loop

Cú pháp

while (condition) { // code }

Ví dụ

var count = 0 while (count < 5) { println("Count: $count") count++ } // 0, 1, 2, 3, 4

🔄 do-while loop

Cú pháp

do { // code (thực thi ít nhất 1 lần) } while (condition)

Ví dụ

var count = 0 do { println("Count: $count") count++ } while (count < 5)

Khác biệt với while

// while - không thực thi nếu điều kiện sai từ đầu var x = 10 while (x < 5) { println("while: $x") // Không in gì x++ } // do-while - luôn thực thi ít nhất 1 lần var y = 10 do { println("do-while: $y") // In "do-while: 10" y++ } while (y < 5)

🎯 Use Cases phổ biến

Đọc input cho đến khi hợp lệ

var input: Int? do { print("Nhập số dương: ") input = readln().toIntOrNull() } while (input == null || input <= 0) println("Bạn đã nhập: $input")

Game loop

var playing = true var lives = 3 while (playing && lives > 0) { println("Đang chơi... Lives: $lives") // Simulate game logic if (kotlin.random.Random.nextBoolean()) { lives-- println("Mất mạng!") } if (lives == 0) { println("Game Over!") playing = false } }

Countdown

var seconds = 10 while (seconds > 0) { println("$seconds...") Thread.sleep(1000) seconds-- } println("🚀 Phóng!")

🛠️ Thực hành

Bài tập 1: Đoán số

import kotlin.random.Random fun main() { val secret = Random.nextInt(1, 101) // 1-100 // TODO: Cho người dùng đoán cho đến khi đúng // Gợi ý: "Lớn hơn" hoặc "Nhỏ hơn" }

Lời giải:

import kotlin.random.Random fun main() { val secret = Random.nextInt(1, 101) var guess: Int? var attempts = 0 println("Đoán số từ 1-100!") do { print("Nhập số: ") guess = readln().toIntOrNull() attempts++ when { guess == null -> println("Vui lòng nhập số!") guess < secret -> println("Lớn hơn!") guess > secret -> println("Nhỏ hơn!") else -> println("🎉 Chính xác! Bạn đoán $attempts lần") } } while (guess != secret) }

Bài tập 2: Tính tổng cho đến khi nhập 0

fun main() { // TODO: Nhập số liên tục và tính tổng // Dừng khi nhập 0 }

Lời giải:

fun main() { var sum = 0 var input: Int println("Nhập các số (0 để dừng):") do { print("> ") input = readln().toIntOrNull() ?: 0 sum += input } while (input != 0) println("Tổng: $sum") }

Bài tập 3: Tìm ước chung lớn nhất (GCD)

fun main() { var a = 48 var b = 18 // TODO: Tìm GCD sử dụng thuật toán Euclid }

Lời giải:

fun main() { var a = 48 var b = 18 println("GCD của $a$b:") while (b != 0) { val temp = b b = a % b a = temp } println("GCD = $a") // 6 }

📱 Trong Android

// Polling for data var retries = 0 val maxRetries = 3 var success = false while (!success && retries < maxRetries) { try { val data = fetchData() success = true } catch (e: Exception) { retries++ delay(1000 * retries) } } // Animation loop do { updateAnimation() Thread.sleep(16) // ~60fps } while (isAnimating)

⚠️ Lưu ý quan trọng

[!CAUTION] Tránh vòng lặp vô hạn:

// ❌ Vòng lặp vô hạn! while (true) { println("Forever...") } // ✅ Có điều kiện thoát while (true) { val input = readln() if (input == "quit") break }

[!TIP] Chọn loop phù hợp:

  • for: Biết trước số lần lặp
  • while: Không biết trước, kiểm tra trước
  • do-while: Cần thực thi ít nhất 1 lần

✅ Checklist - Tự kiểm tra

Sau bài học này, bạn có thể:

  • Sử dụng while loop
  • Sử dụng do-while loop
  • Phân biệt khi nào dùng while vs do-while
  • Tránh tạo vòng lặp vô hạn
  • Áp dụng cho input validation và game logic

Tiếp theo: Break và Continue

Last updated on