2012-12-02 161 views
1

我不知道爲什麼我無法獲得用if和else if語句編寫簡單計算的正確方法。使用IF計算,否則IF語句

所有的變量只是返回一個「0.0」的值,我不能猜出什麼是錯的?你能幫我解決這個問題嗎?

這是我的代碼:

public class MonthlyComputation extends MyActivity 
{ 
String civil_status; 

public void DoComputation() 
{ 

    final EditText net_salary = (EditText) findViewById(R.id.et_net_monthly); 
    final EditText tax_due = (EditText) findViewById(R.id.et_taxdue); 
    final Button btn_compute = (Button) findViewById(R.id.btn_compute_from_monthly); 
    final TextView txt3 = (TextView) findViewById(R.id.textView3); 
    final TextView txt4 = (TextView) findViewById(R.id.textView4); 

    final TextView txt5 = (TextView) findViewById(R.id.textView5); 
    final TextView txt6 = (TextView) findViewById(R.id.textView6); 


    btn_compute.setOnClickListener(new Button.OnClickListener() 
    { 

     @Override 
     public void onClick(View v) 
     { 

      double netSalary, taxDue, rate = 0, exemption = 0, subtrahend = 0, withRate; 
      String ns, td, r, e, s, wr; 

      ns = net_salary.getText().toString(); 
      netSalary = Double.parseDouble(ns); 

      /* Single or Married with no dependent */ 

      if ((civil_status == "SME") && (netSalary >= 4167) && (netSalary < 5000)) 
      { 
       rate = 0.05; 
       exemption = 0.00; 
       subtrahend = 4167; 
      } 

      else if ((civil_status == "SME") && (netSalary >= 5000) && (netSalary < 6667)) 
      { 
       rate = 0.1; 
       exemption = 41.67; 
       subtrahend = 5000; 
      } 

      taxDue = netSalary - subtrahend; 
      withRate = taxDue * rate; 
      taxDue = withRate + exemption; 
      tax_due.setText(Double.toString(taxDue)); 

      td = String.valueOf(taxDue); 
      e = String.valueOf(exemption); 
      s = String.valueOf(subtrahend); 
      r = String.valueOf(rate); 

      txt3.setText(td); 
      txt4.setText(e); 
      txt5.setText(s); 
      txt6.setText(r); 

     } 
    }); 
} 

回答

12

永遠不要使用==比較(一般和對象)String,你最有可能得到false,因爲它比較對象引用,而不是值。

更多信息請參見該另一個問題:Java String.equals versus ==

該如何解決?改爲使用.equals()

... 
if ("SME".equals(civil_status) && (netSalary >= 4167) && (netSalary < 5000)) 
{ 
    rate = 0.05; 
    exemption = 0.00; 
    subtrahend = 4167; 
} 
... 
+0

非常感謝! :D –

+0

不客氣! –