跳轉到內容

Rexx 程式設計/Rexx 指南/switch 條件語句

來自華夏公益教科書,開放的書籍,開放的世界

Rexx 允許我們的程式逐一檢查眾多可能的情況,直到找到實際情況。執行此操作的關鍵字是 SELECT、WHEN、THEN 和 OTHERWISE。列出所有情況及其可能的響應後,我們使用 END 關閉結構。

/* Try to tell someone whether they have a fever or not. */
say "Enter your temperature in degrees Celsius:"
pull degrees
select
 when DataType(degrees) \= "NUM" then
  say "That's not a number. I can't help you."
 when degrees < 36.5 then
  say "Your body temperature is a bit low."
 when degrees > 37.5 then
  say "I think you have a fever."
 otherwise
  say "You're temperature seems normal."
end
/* NOT real medical advice -- just an example! */

示例指令碼在接收輸入後開始執行各種測試。首先,它檢查輸入是否為數字。然後,它檢查溫度是否過低或過高。如果這兩個條件都沒有滿足,它將報告正常溫度。滿足任何 WHEN 條件後,程式將停止檢查,執行一行程式碼,並跳至結尾。

多行響應

[編輯 | 編輯原始碼]

您可以使用 DO/END 塊來實現更復雜的功能。

say "Would you like to convert feet to meters or meters to feet?"
say "Type M to enter a number of meters or F to enter a number of feet."
pull choice
select
 when choice = "M" then do
  say "Enter a number of meters:"
  pull meters
  feet = meters / 0.3048
  say "That's equal to" feet "ft."
 end
 when choice = "F" then do
  say "Enter a number of feet:"
  pull feet
  meters = feet * 0.3048
  say "That's equal to" meters "m."
 end
 otherwise say "I don't understand what you entered."
end

測試多個變數

[編輯 | 編輯原始碼]

WHEN 條件可以像我們想要的那樣複雜。這裡有著名的 FIZZBUZZ 程式,它按正常順序計數,但 3、5 和 15 的倍數除外。

/* FizzBuzz */
do count = 1 to 30
 divisible_by_3 = count // 3 = 0
 divisible_by_5 = count // 5 = 0
 select
  when divisible_by_3 & divisible_by_5 then
   say "FIZZBUZZ"
  when divisible_by_3 then
   say "FIZZ"
  when divisible_by_5 then
   say "BUZZ"
  otherwise
   say count
 end
end

這難道不是和 IF/ELSE 一樣嗎?

[編輯 | 編輯原始碼]

是的。如果您已經瞭解了 IF 語句,您可以使用它們編寫相同的程式碼。SELECT 只是用於將相關的條件結構分組的便利方法,尤其是在您需要很多 ELSE IF 行的情況下。

/* Code with SELECT: */
select
 when number < 0 then type = 'negative'
 when number > 0 then type = 'positive'
 otherwise type = 'neutral'
end
/* Same code with IF */
if number < 0 then type = 'positive'
else if number > 0 then type = 'positive'
else type = 'neutral'

為什麼是 "switch"?

[編輯 | 編輯原始碼]

這種控制結構有時被稱為 "switch 條件語句",因為一些其他語言使用 "switch" 關鍵字來分析單個變數,並根據表示不同可能值的不同情況分支到不同的執行路徑。它通常只適用於有限數量的可能值,並且不一定自動跳過其他測試。Rexx 版本更詳細,但也更通用。SELECT 通常在 Rexx 中使用,而其他語言則必須使用 IF/ELSE。

華夏公益教科書