ZetCode

FreeBasic Continue 关键字

最后修改于 2025 年 6 月 23 日

FreeBasic 的 Continue 关键字是一个循环控制语句,它跳过当前迭代并进入下一个周期。它有助于根据条件选择性地处理循环内的元素。

基本定义

在 FreeBasic 中,Continue 用于循环(For、While、Do)中,以跳过当前迭代中剩余的代码。遇到时,它会跳转到循环的条件检查。

Continue 语句通过允许选择性处理使循环更加灵活。它经常与条件语句一起使用,以跳过特定情况而不退出整个循环。

For 循环中的 Continue

本示例演示了如何使用 Continue 来跳过 For 循环中的偶数。

continue_for.bas
For i As Integer = 1 To 10
    If (i Mod 2) = 0 Then
        Continue For
    End If
    Print i; " is odd"
Next

该循环仅打印奇数。当检测到偶数时,Continue 会跳过 Print 语句。然后循环继续到下一个值。

While 循环中的 Continue

在这里,我们使用 Continue 来跳过 While 循环中的负数处理。

continue_while.bas
Dim n As Integer = -5

While n <= 5
    If n < 0 Then
        n += 1
        Continue While
    End If
    Print "Processing"; n
    n += 1
Wend

该循环仅处理非负数。当为负数时,它会增加 n 并继续到下一次迭代。请注意,我们必须在 Continue 之前增加 n。

Do 循环中的 Continue

本示例展示了 Do 循环中的 Continue,用于跳过字符串处理中的元音字母。

continue_do.bas
Dim s As String = "FreeBasic"
Dim i As Integer = 0

Do While i < Len(s)
    Dim c As String = Mid(s, i + 1, 1)
    If InStr("aeiouAEIOU", c) Then
        i += 1
        Continue Do
    End If
    Print c; " is a consonant"
    i += 1
Loop

该循环处理每个字符,跳过元音字母。当找到元音字母时,它会增加索引并继续。只打印辅音字母。

嵌套循环中的 Continue

当在嵌套结构中使用 Continue 时,它只会影响最内层的循环。

continue_nested.bas
For i As Integer = 1 To 3
    For j As Integer = 1 To 3
        If j = 2 Then
            Continue For
        End If
        Print "i:"; i; " j:"; j
    Next
Next

当 j 等于 2 时,内层循环会跳过迭代。外层循环正常继续。Continue 只影响它直接包含的循环。

条件逻辑中的 Continue

我们可以将 Continue 与复杂的条件结合起来,以实现复杂的循环控制。

continue_conditional.bas
For i As Integer = 1 To 20
    If (i Mod 3 <> 0) And (i Mod 5 <> 0) Then
        Continue For
    End If
    Print i; " is divisible by 3 or 5"
Next

这会打印出 3 或 5 的倍数。Continue 会跳过不满足任一条件的数字。逻辑可以通过 If-Else 进行反转。

无限循环中的 Continue

在本例中,我们使用 Continue 来控制一个无限循环,直到满足特定条件。无限循环是通过使用没有终止条件的 Do 循环创建的。

continue_infinite.bas
Dim count As Integer = 0

Do
    count += 1
    If count < 5 Then
        Continue Do
    End If
    Print "Count reached"; count
    If count >= 10 Then
        Exit Do
    End If
Loop

循环会跳过打印,直到 count 达到 5。打印后,它会检查退出条件。Continue 有助于在满足标准之前延迟处理。

Continue 与 Exit 对比

本示例在循环控制中对比了 ContinueExit

continue_vs_exit.bas
For i As Integer = 1 To 5
    If i = 3 Then
        'Exit For   ' Would stop the entire loop
        Continue For ' Skips only this iteration
    End If
    Print i
Next
Print "Loop finished"

使用 Continue,除了 3 之外的所有数字都会被打印。如果取消注释 Exit,则在循环终止前只会打印 1 和 2。

最佳实践

本教程通过实际示例涵盖了 FreeBasic Continue 关键字,展示了其在不同循环场景中的用法。

作者

我叫 Jan Bodnar,是一位热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出所有 FreeBasic 教程