String str = "";
switch (str) { // str 永遠為空串
case "1": ... break;
case "2": ... break;
case "3": ... break;
default: System.out.println("稅收: 0");
}
str 從未賦值,永遠為 "",不匹配任何 case,直接走 default 輸出 0。switch 完全不適合。| 月收入區間 | 稅率/速算扣除 |
|---|---|
| ≤ 3500 | 0% |
| 3500 ~ 5000 | (收入-3500)×3% |
| 5000 ~ 8000 | (5000-3500)×3% + (收入-5000)×10% |
| > 8000 | 前兩級 + (收入-8000)×20% |
import java.util.Scanner;
public class Tax {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入月工資: ");
double income = sc.nextDouble();
double tax = 0;
if (income <= 3500) {
tax = 0;
} else if (income <= 5000) {
tax = (income - 3500) * 0.03;
} else if (income <= 8000) {
tax = 1500 * 0.03 + (income - 5000) * 0.10;
} else {
tax = 1500 * 0.03 + 3000 * 0.10 + (income - 8000) * 0.20;
}
System.out.printf("應繳個稅: %.2f 元%n", tax);
}
}
switch、str,直接用 if-else if 區間判斷。稅率區間用 if-else,**拒絕 switch 硬套**,代碼清爽、邏輯正確、易維護!