gpt4 book ai didi

java - 使用 IF、ELSE IF 语句计算

转载 作者:行者123 更新时间:2023-11-29 09:44:35 25 4
gpt4 key购买 nike

我不知道为什么我无法使用 if 和 else 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);

}
});
}

最佳答案

永远不会使用==来比较String(和一般的对象),你很可能会得到false 因为它比较对象引用,而不是值。

有关更多信息,请参阅其他问题:Java String.equals versus ==

解决方案?使用 .equals() 代替:

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

关于java - 使用 IF、ELSE IF 语句计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13670921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com