Apex - While 迴圈



Apex 程式語言中的一個 while 迴圈語句會重複執行目標語句,只要給定條件為真。這在某種程度上類似於 do-while 迴圈,但有一個主要區別。它只有在條件為真時才會執行程式碼塊,但在 do-while 迴圈中,即使條件為假,它也會至少執行一次程式碼塊。

語法

while (Boolean_condition) { execute_code_block }

流程圖

Apex Wile Loop

此處 while 迴圈的關鍵點在於迴圈可能永遠不會執行。當條件得到測試且結果為假時,迴圈體將被跳過並且 while 迴圈後的第一條語句將被執行。

示例

在該示例中,我們將實現與針對 do-while 迴圈所做的相同的場景,但這次將使用 While 迴圈。它將更新 10 條記錄的描述。

//Fetch 20 records from database
List<apex_invoice_c> InvoiceList = [SELECT Id, APEX_Description_c,
   APEX_Status_c FROM APEX_Invoice_c LIMIT 20];
Integer i = 1;

//Update ONLY 10 records
while (i< 10) {
   InvoiceList[i].APEX_Description__c = 'This is the '+i+'Invoice';
   System.debug('Updated Description'+InvoiceList[i].APEX_Description_c);
   i++;
}
apex_loops.htm
廣告