FreeBasic Do While 关键字
最后修改日期:2025 年 6 月 16 日
FreeBasic 的 Do While 关键字创建一个循环,只要条件保持为真,就会重复执行一段代码。它在每次迭代之前检查条件。
基本定义
在 FreeBasic 中,Do While 是一种循环结构,只要其条件求值为真,它就会继续执行。该条件在每次迭代开始时进行检查。
语法包括 Do While、一个条件、循环体和标记结束的 Loop。当您需要重复代码一个未知的次数时,它很有用。
简单计数器循环
此示例使用 Do While 演示了一个基本的计数器。
Dim counter As Integer = 1
Do While counter <= 5
Print "Iteration: "; counter
counter += 1
Loop
Print "Loop finished"
循环在 counter 小于或等于 5 时运行。每次迭代都会打印当前值并增加 counter。当 counter 达到 6 时,条件变为假,循环终止。
用户输入验证
Do While 非常适合验证用户输入,直到其满足标准为止。
Dim age As Integer
Do While age < 1 Or age > 120
Input "Enter your age (1-120): ", age
Loop
Print "Valid age entered: "; age
此循环会一直提示输入年龄,直到输入一个介于 1 到 120 之间的值。条件检查无效值,使循环保持活动状态,直到收到有效输入为止。
读取直到哨兵值
Do While 可以处理输入,直到出现特定的哨兵值。
Dim number As Integer
Dim sum As Integer = 0
Print "Enter numbers (0 to stop):"
Do While True
Input "", number
If number = 0 Then Exit Do
sum += number
Loop
Print "Sum of numbers: "; sum
此示例使用无限循环和 Exit Do,在输入零时退出。它会累加数字,直到哨兵值 (0) 终止输入。
文件读取循环
Do While 常用于读取文件,直到到达文件末尾。
Dim fileNum As Integer = FreeFile()
Open "data.txt" For Input As #fileNum
Dim line As String
Dim lineCount As Integer = 0
Do While Not EOF(fileNum)
Line Input #fileNum, line
lineCount += 1
Print "Line "; lineCount; ": "; line
Loop
Close #fileNum
Print "Total lines read: "; lineCount
循环在 EOF (End Of File) 为假时继续。每次迭代读取一行并增加计数器。这种模式是逐行处理文本文件的标准方法。
菜单系统
Do While 可以驱动交互式菜单系统,直到退出为止。
Dim choice As String
Do While choice <> "4"
Print "1. Option One"
Print "2. Option Two"
Print "3. Option Three"
Print "4. Exit"
Input "Select: ", choice
Select Case choice
Case "1": Print "Option One selected"
Case "2": Print "Option Two selected"
Case "3": Print "Option Three selected"
Case "4": Print "Exiting..."
Case Else: Print "Invalid choice"
End Select
Loop
此菜单系统会显示选项,直到用户选择 4 退出。Do While 条件会检查退出命令,使菜单循环直观且易于维护。
游戏循环
Do While 非常适合在游戏活动期间运行的游戏循环。
Dim gameOver As Boolean = False
Dim score As Integer = 0
Dim lives As Integer = 3
Do While Not gameOver
' Game logic would go here
score += 10
Print "Score: "; score; " Lives: "; lives
If score >= 100 Then
gameOver = True
Print "You won!"
ElseIf Rnd() < 0.1 Then
lives -= 1
If lives <= 0 Then
gameOver = True
Print "Game Over!"
End If
End If
Loop
这个简化的游戏循环在 gameOver 为假时运行。它会更新分数并检查输赢条件。布尔标志根据游戏状态控制循环的执行。
嵌套的 Do While 循环
Do While 循环可以嵌套以处理复杂的重复任务。
Dim outer As Integer = 1
Do While outer <= 3
Dim inner As Integer = 1
Print "Outer loop: "; outer
Do While inner <= outer
Print " Inner loop: "; inner
inner += 1
Loop
outer += 1
Loop
此示例展示了嵌套的 Do While 循环。外层循环运行 3 次,而内层循环的迭代次数随外层循环的每次传递而增加。嵌套循环对于多维处理很有用。
最佳实践
- 初始化:在 Do While 之前初始化循环变量。
- 终止:确保条件最终会变为假。
- 可读性:在条件中使用有意义的变量名。
- 复杂条件:将复杂条件分解为变量。
- Exit Do:谨慎使用,仅用于清晰的异常情况。
本教程介绍了 FreeBasic 的 Do While 关键字,并通过实际示例展示了其在不同场景下的用法。