_三元運算子_是簡單 if/else 述句的輕量、精簡替代方案。
它通常用於回傳述句(但並不限於此),只需要一行就能做出決定:運算式為 true 時回傳左邊的值,為 false 時回傳右邊的值,如下所示:
boolean expr = 0 != 200;
// Ternary statement
int value = expr ? 22 : 33;
// => 22
許多簡單的 if/else 運算式都可以用_三元運算子_簡化。
在這個練習中,你將實作計算員工當月總薪資的規則。 International Siderurgy Company(ISC)需要協助計算員工薪資,並考量各種可能影響最終薪資的因素。
你有三個任務,而且應該使用三元運算子,而不是 if/else 敘述來實作。
實作 salaryMultiplier 方法,它會根據員工曠職的天數回傳薪資倍率。
如果員工曠職至少五天,就扣減 15%。
int daysSkipped = 3;
salaryMultiplier(daysSkipped);
// => 1.0
daysSkipped = 7;
salaryMultiplier(daysSkipped);
// => 0.85
實作 bonusMultiplier 和 bonusForProductsSold 方法。
ISC 會為每售出一件產品支付十個貨幣單位,而如果員工售出二十件以上的產品,倍率就會提高到十三。
bonusMultiplier 應該決定要套用哪個倍率,而 bonusForProductSold 則應該以貨幣單位回傳獎金總額。
int productsSold = 21;
bonusMultiplier(productsSold);
// => 13
bonusForProductsSold(productsSold);
// => 273
productsSold = 5;
bonusMultiplier(productsSold);
// => 10
bonusForProductsSold(productsSold);
// => 50
實作 finalSalary 方法。
它應該將基本薪資 1000.00 乘上薪資倍率,加上獎金,然後回傳結果。
不過,薪資上限為 2000.00。
int daysSkipped = 2;
int productsSold = 3;
finalSalary(daysSkipped, productsSold);
// => 1030.00
productsSold = 90;
finalSalary(daysSkipped, productsSold);
// => 2000.00