首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 計算個人所得稅:switch 誤用導致恆輸出 0,改用 if-else 秒解決

     編輯:程式設計疑難解答

錯誤代碼核心

String str = "";
switch (str) { // str 永遠為空串
    case "1": ... break;
    case "2": ... break;
    case "3": ... break;
    default: System.out.println("稅收: 0");
}

根因

  • str 從未賦值,永遠為 "",不匹配任何 case,直接走 default 輸出 0。
  • 題目本質是**區間判斷**,switch 完全不適合。

正確邏輯:分級累進稅率

月收入區間稅率/速算扣除
≤ 35000%
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);
    }
}

關鍵點

  1. 刪除 switch、str,直接用 if-else if 區間判斷。
  2. 累進稅率:**只對超額部分按對應稅率計算**,而非全額按最高稅率。
  3. 輸出保留兩位小數,符合貨幣習慣。

稅率區間用 if-else,**拒絕 switch 硬套**,代碼清爽、邏輯正確、易維護!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved