學習軌道
/
Java
Java
/
練習
/
薪資計算機
薪資計算機

薪資計算機

學習練習

簡介

三元運算子

_三元運算子_是簡單 if/else 述句的輕量、精簡替代方案。 它通常用於回傳述句(但並不限於此),只需要一行就能做出決定:運算式為 true 時回傳左邊的值,為 false 時回傳右邊的值,如下所示:

boolean expr = 0 != 200;

// Ternary statement
int value = expr ? 22 : 33;
// => 22

許多簡單的 if/else 運算式都可以用_三元運算子_簡化。

說明

在這個練習中,你將實作計算員工當月總薪資的規則。 International Siderurgy Company(ISC)需要協助計算員工薪資,並考量各種可能影響最終薪資的因素。

你有三個任務,而且應該使用三元運算子,而不是 if/else 敘述來實作。

1. 決定薪資倍率

實作 salaryMultiplier 方法,它會根據員工曠職的天數回傳薪資倍率。 如果員工曠職至少五天,就扣減 15%。

int daysSkipped = 3;
salaryMultiplier(daysSkipped);
// => 1.0

daysSkipped = 7;
salaryMultiplier(daysSkipped);
// => 0.85

2. 計算售出產品的獎金

實作 bonusMultiplier 和 bonusForProductsSold 方法。 ISC 會為每售出一件產品支付十個貨幣單位,而如果員工售出二十件以上的產品,倍率就會提高到十三。 bonusMultiplier 應該決定要套用哪個倍率,而 bonusForProductSold 則應該以貨幣單位回傳獎金總額。

int productsSold = 21;
bonusMultiplier(productsSold);
// => 13
bonusForProductsSold(productsSold);
// => 273

productsSold = 5;
bonusMultiplier(productsSold);
// => 10
bonusForProductsSold(productsSold);
// => 50

3. 計算員工的最終薪資

實作 finalSalary 方法。 它應該將基本薪資 1000.00 乘上薪資倍率,加上獎金,然後回傳結果。 不過,薪資上限為 2000.00。

int daysSkipped = 2;
int productsSold = 3;
finalSalary(daysSkipped, productsSold);
// => 1030.00

productsSold = 90;
finalSalary(daysSkipped, productsSold);
// => 2000.00
透過 GitHub 編輯 連結會在新視窗或分頁中開啟
Java Exercism

準備好開始 薪資計算機 了嗎?

註冊 Exercism,透過 26 個概念158 個練習 和真人引導來學習並精通 Java,全部免費。