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 语句,您可以使用它们编写相同的代码。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" 关键字来分析单个变量,并根据表示不同可能值的不同情况分支到不同的执行路径。它通常只适用于有限数量的可能值,并且不一定自动跳过其他测试。Rexx 版本更详细,但也更通用。SELECT 通常在 Rexx 中使用,而其他语言则必须使用 IF/ELSE。