Apex - if else 语句

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

语法

if boolean_expression {
   /* 如果布尔表达式为 true,则语句将执行 */
} else {
   /* 如果布尔表达式为 false,则语句将执行 */
}

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

流程图

if-else 语句

示例

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

//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 条件。

apex_decision_making.html