根据给定的条件,条件语句允许您的逻辑部件在一个或多个操作之间进行选择。如果您熟悉任何其它过程化编程语言,您或许知道如何使用 EGL 中提供的以下条件语句:
if 语句是 EGL 中最简单的条件语句。if 语句对逻辑表达式进行求值,如果该表达式为 true,则执行 if 语句中的代码。否则不会执行 if 语句中的代码。以下是 if 语句的一个示例:
if (myVariable1 == myVariable2) //This code executes only if myVariable1 is equal to myVariable2 myVariable1 = 5; myVariable3 = 10; end
(可选)可将 else 语句添加至 if 语句。仅当 if 语句中的逻辑表达式为 false 时才会执行 else 语句中的代码。以下是包括 else 语句的 if 语句的示例:
if (myVariable1 == myVariable2) //This code executes only if myVariable1 is equal to myVariable2 myVariable1 = 5; myVariable3 = 10; else //This code executes only if myVariable1 is not equal to myVariable2 myFunction(); myVariable2 = 20; end
可以将 if 语句嵌套至任何级别。嵌套 if 语句允许您执行更复杂的逻辑,如在下面的示例中所示:
if (myVariable1 > myVariable2) myMessage = "myVariable1 is greater than myVariable2"; else if (myVariable1 < myVariable3) myMessage = "myVariable1 is less than myVariable2"; else myMessage = "myVariable1 and myVariable2 are equal"; end end
单个 if else 语句只能在两部分 EGL 代码之间作出选择:如果逻辑表达式为 true 执行一部分代码,如果逻辑表达式为 false 则执行另一部分代码。为代码提供更多选项的一种方法是使用 case 语句。case 语句对表达式进行求值并在可能值列表中查找匹配项。以下是 case 语句的一个示例:
case (myCharVariable) when ("A") myMessage2 = "myCharVariable equals A"; when ("B") myMessage2 = "myCharVariable equals B"; otherwise myMessage2 = "myCharVariable is not A or B"; end
名为 if else 和 case 的帮助主题中提供了有关条件语句的更多信息。
要为条件语句创建逻辑表达式,需要使用逻辑运算符来比较两个变量或为条件语句设置条件。以下是 EGL 中提供的一些常用运算符:
在下面的步骤中,将创建使用条件语句来响应用户输入的 Web 页面。
IfTest
package pagehandlers; PageHandler IfTest {view="IfTest.jsp", onPageLoadFunction=onPageLoad} //Variables a int {value=10}; b int {value=20}; c int {value=30}; msg char(50); Function onPageLoad() end Function testSimpleIf() if (a > b) msg = "a > b"; else if (b > a) msg = "b > a"; else msg = "b = a"; end end end Function compoundAnd() if ((a > b) && (a > c)) msg = "a is highest value"; else if ((b > a) && (b > c)) msg = "b is highest value"; else if ((c > a) && (c > b)) msg = "c is highest value"; else msg = "Two or three values are equal."; end end end end Function compoundOr() if ((a > b) || (a > c)) msg = "a > b or a > c"; else if ((b > a) || (b > c)) msg = "b > a, or b > c"; else if ((c > a) && (c > b)) msg = "c is highest (a and b are equal)"; else msg = "All values are equal"; end end end end Function testNotEqual() if (a != b) msg = "a is not equal to b"; else msg = "a equals b"; end end end
以下是一些有关刚才添加的代码的技术说明:
“插入控件”窗口看起来应如下所示:
页面需要四个按钮,每个按钮将绑定至 PageHandler 的四个函数中的每一个函数。
该页面看起来应如下所示:
现在,您可以开始进行练习 1.7:循环了。