目录

if...else statement

if语句后面可以跟一个可选的else语句,该语句在布尔表达式为false时执行。

语法 (Syntax)

if boolean_expression {
   /* statement(s) will execute if the boolean expression is true */
} else {
   /* statement(s) will execute if the boolean expression is false */
}

如果布尔表达式的计算结果为true,那么将执行if block of code ,否则将执行代码块。

流程图 (Flow Diagram)

if-else声明

例子 (Example)

假设,我们的化学公司拥有两类客户 - 高级和普通。 根据客户类型,我们应该为他们提供折扣和其他好处,如售后服务和支持。 以下程序显示了相同的实现。

//Execute this code in Developer Console and see the Output
String customerName = 'Glenmarkone'; //premium customer
Decimal discountRate = 0;
Boolean premiumSupport = false;
if (customerName == 'Glenmarkone') {
   discountRate = 0.1; //when condition is met this block will be executed
   premiumSupport = true;
   System.debug('Special Discount given as Customer is Premium');
}else {
   discountRate = 0.05; //when condition is not met and customer is normal
   premiumSupport = false;
   System.debug('Special Discount Not given as Customer is not Premium');
}

由于'Glenmarkone'是高级客户,因此if块将根据条件执行,在其他情况下,将触发else条件。

↑回到顶部↑
WIKI教程 @2018