Rexx - 決策



決策結構要求程式設計師指定一個或多個條件,由程式進行評估或測試。

下圖顯示了大多數程式語言中典型的決策結構的通用形式。

Decision Making

如果條件確定為true,則執行一個或多個語句;或者,如果條件確定為false,則可以選擇執行其他語句。

讓我們看看 Rexx 中可用的各種決策語句。

序號 語句及描述
1 If 語句

第一個決策語句是if語句。if語句由一個布林表示式和一個或多個語句組成。

2 If-else 語句

下一個決策語句是 if-else 語句。if語句後面可以跟一個可選的 else 語句,當布林表示式為 false 時執行。

巢狀 If 語句

有時需要在彼此內部巢狀多個 if 語句,這在其他程式語言中也是可能的。在 Rexx 中也可以做到這一點。

語法

if (condition1) then 
   do 
      #statement1 
   end 
else 
   if (condition2) then 
      do 
      #statement2 
   end

流程圖

巢狀if語句的流程圖如下:

Nested If Statement

讓我們來看一個巢狀if語句的例子:

示例

/* Main program */ 
i = 50 
if (i < 10) then 
   do 
      say "i is less than 10" 
   end 
else 
if (i < 7) then 
   do 
      say "i is less than 7" 
   end 
else 
   do 
      say "i is greater than 10" 
   end 

上述程式的輸出將是:

i is greater than 10 

Select 語句

Rexx 提供 select 語句,可用於根據 select 語句的輸出執行表示式。

語法

此語句的通用形式為:

select 
when (condition#1) then 
statement#1 

when (condition#2) then 
statement#2 
otherwise 

defaultstatement 
end 

此語句的通用工作原理如下:

  • select 語句有一系列 when 語句來評估不同的條件。

  • 每個when 子句都有一個不同的條件需要評估,然後執行後續語句。

  • 如果之前的 when 條件不評估為 true,則使用 otherwise 語句執行任何預設語句。

流程圖

select語句的流程圖如下:

Select Statement

以下程式是 Rexx 中 case 語句的示例。

示例

/* Main program */ 
i = 50 
select 
when(i <= 5) then 
say "i is less than 5" 

when(i <= 10) then 
say "i is less than 10" 

otherwise 
say "i is greater than 10" 
end

上述程式的輸出將是:

i is greater than 10 
廣告