Do...Loop ステートメント

Do...Loop ステートメントは、そのブーリアン演算テスト式が True である限りステートメントを反復処理します。ブーリアン演算テスト式は、Do...Loop ステートメントの最初または最後に置くことができます。

次の構文では、ループの最初にテストがある Do...Loop ステートメントを適用します。

Do <While | Until> <expression>
   <statements>
Loop

次の例は、Do While...Loop 構文を使用します。

Dim counter As Integer = 0
Dim total As Integer = 0

Do While counter < 10
   total = total + counter
   counter = counter + 1
Loop

または、前の例で Do While の代わりに Do Until を使用することもできます。この場合、Do Until ステートメントは次のように表されます。

Do Until counter = 10

次の構文では、ループの最後にテストがある Do...Loop ステートメントを適用します。

Do
   <statements>
Loop <While | Until> <expression>

テスト式が Do...Loop ステートメントの最後に置かれる場合、ループ内のステートメント ブロックが少なくとも 1 回実行されます。

次の例は先ほどの Do While...Loop の例と似ていますが、Do...Loop While 構文を使用します。

Dim counter As Integer = 0
Dim total As Integer = 0

Do
   total = total + counter
   counter = counter + 1
Loop While counter < 10

または、前の例で Loop While の代わりに Loop Until を使用することもできます。この場合、Loop Until ステートメントは次のように表されます。

Loop Until counter =10

次の例に示すように、Exit ステートメントを使用することで Do...Loop ステートメントから抜け出すことができます。

この例では、パラメータがいくつかの項目の単位あたりの重量を指定します。荷重ルール内の Do...Loop ステートメントにより(最大 10 単位の)合計荷重に重量が加算されます。荷重には 25 の制限があります。追加の単位重量が加算されるため、合計荷重はこの制限と比較されてシステム メッセージが生成されます。荷重が制限を超えると、メッセージに警告が追加され、反復が停止します。コントロールが Do...Loop ステートメント外に移ります。

Parameter Rule unitWeight As Integer = 5

Rule load As Number
   Dim counter As Integer = 1
   Dim limit As Number = 25.0
   Dim strItem As String = " item."
   Do
      If counter > 1 Then
         strItem = " items."
      End If
      load = load + unitWeight
      If load > limit Then
         printValue("Warning: Load = " + stringValue(load) + _
            "kg for " + stringValue(counter) + strItem + " " + _
            stringValue(limit) + "kg limit exceeded!")
         Exit Do
      Else
         printValue("Load = " + stringValue(load) + _
         "kg for " + stringValue(counter) + strItem)
      End If
      counter = counter + 1
   Loop While counter <= 10
End Rule
注: 詳細については、「Exit ステートメント」を参照してください。