2011-02-24 79 views
1

我作爲學校的一項任務我必須計算一個數字,這是一個公民的稅收總額。我在文本文件中給出了閾值的數量,閾值和每個閾值的速率。一個例子是計算我的收入計劃中的一部分稅收與稅率和稅率在java

Threshold Rate 
$15,000 15% 
$29,000 20% 
$50,000 25% 

公民,其淨收入爲$ 55,000名會支付: $ 15,000個* 0%+ $ 14,000個* 15%+ $ 21,000名* 20%+ $ 5,000個* 25%= $ 7,550

我已經開始了我這裏

private void computeTaxOwed(Citizen cit, TaxSchedule sked){ 

    double netIncome = cit.getNetIncome(); 
    double totTaxPaid = cit.getTotTaxPaid(); 

    int levels = sked.getNumLevels(); 
    double[] threshold = sked.getThreshold(); 
    double[] rate = sked.getRate(); 

    double taxOwd = 0; 

    for(int i = levels; i>0; i--){ 
     taxOwd = ((netIncome-threshold[i])*rate[i]); 
    } 

方法我知道這不會給正確的輸出,我只是無法弄清楚如何使這項工作的算法。如果我可以提取兩個數組的值並將它們分別保存到一個單獨的變量中,我可以很容易地得到正確的輸出,但我認爲這非常混亂,而不是最好的方式。

任何想法將不勝感激!

+0

記錄公民尚未納稅的部分收入,並更新通過循環的每次通過。有你的線索。 :) – 2011-02-24 02:34:25

回答

1
class Main { 

    public static void main(String[] args) { 

     double netIncome = 55000; 

     int levels = 3; 
     double[] threshold = {0, 15000, 29000, 50000}; 
     double[] rate = {0, 15,20,25}; 

     double taxOwd = 0; 

     double taxableIncome = 0; 
     double netIncomeLeft = netIncome; 

     for (int i = levels; i > 0; i--) { 
      taxableIncome = netIncomeLeft - threshold[i]; 
      taxOwd += taxableIncome * (rate[i]/100); 
      netIncomeLeft = threshold[i]; 
     } 
     System.out.println("taxOwd " + taxOwd); 
    } 
} 

或在更緊湊的時尚:

 for (int i = levels; i > 0; i--) { 
      taxOwd += ((netIncome - threshold[i]) * (rate[i]/100)); 
      netIncome = threshold[i]; 
     } 
+0

謝謝先生,現在看來我真的很簡單! – Cheesegraterr 2011-02-24 02:58:17

+0

假設開始'netIncome'是1,000.00,'taxOwd'是什麼?看起來像退款給我! – NealB 2012-05-03 20:51:46

3

AlfaTek建議的答覆不處理的話,在0-15000支架率爲零,因爲我> 0,而不是我> = 0作爲for循環的終止條件。以下片段涉及此問題:

double netIncomeLeft = netIncome; 
    double taxOwd = 0; 

    for (int i = threshold.length - 1; i >= 0; i--) { 
     if(netIncomeLeft < threshold[i]) { 
      //continue on if current tier is greater than the remainder 
      continue; 
     } 

     taxOwd += (netIncomeLeft - threshold[i]) * rate[i]/100.0; 
     netIncomeLeft = threshold[i]; 
    }