我是一个初学Android程序员,我正在尝试制作小费计算器。这是我迄今为止编写的代码。我有两个问题。首先,为什么我的计算按钮不起作用?第二个是,如果这段代码是干净的?或者我是在错误的轨道上?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Fooi extends Activity implements OnClickListener {
EditText etBill, etPers, etPerc;
TextView tvTotal, tvTip, tvPerson;
Button bCalc, bReset;
double billamount = 0;
double percentage = 0;
double persons = 0;
double tipamount = 0;
double totaltopay = 0;
double perperson = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fooi);
Controls();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bCalculate:
if (billamount == 0 | percentage == 0 | persons == 0) {
// toast text
} else {
Calculate();
}
break;
case R.id.bReset:
etBill.setText("");
etPerc.setText("");
etPers.setText("");
break;
}
}
private void Calculate() {
billamount = Double.parseDouble(etBill.getText().toString());
percentage = Double.parseDouble(etPerc.getText().toString());
persons = Double.parseDouble(etPers.getText().toString());
tipamount = (billamount * percentage) / 100;
totaltopay = billamount + tipamount;
perperson = totaltopay / persons;
tvTip.setText(Double.toString(tipamount));
tvTotal.setText(Double.toString(totaltopay));
tvPerson.setText(Double.toString(perperson));
}
private void Controls() {
bCalc = (Button) findViewById(R.id.bCalculate);
bReset = (Button) findViewById(R.id.bReset);
bCalc.setOnClickListener(this);
bReset.setOnClickListener(this);
tvTotal = (TextView) findViewById(R.id.tvTotal);
tvTip = (TextView) findViewById(R.id.tvBill);
tvPerson = (TextView) findViewById(R.id.tvPerPerson);
etBill = (EditText) findViewById(R.id.etBill);
etPerc = (EditText) findViewById(R.id.etPercentage);
etPers = (EditText) findViewById(R.id.etPerson);
}
}
关于这行代码,我不确定。 if (billamount == 0 | percentage == 0 | persons == 0) {
// toast text
我希望它只在三个EditTexts被填充时计算。有人可以告诉我,如果我错了吗?
提前致谢!!
答案 0 :(得分:0)
代码写得很好,除了你的2件事: 1)你的if条款
if (billamount == 0 | percentage == 0 | persons == 0)
在条件之间到“OR”,使用双管而不是单个管道,所以:
if (billamount == 0 || percentage == 0 || persons == 0)
2)在计算之前你没有从editTexts获取值... 将这些行(并添加空检查)移动到计算按钮上的onClick案例的开头:
billamount = Double.parseDouble(etBill.getText().toString());
percentage = Double.parseDouble(etPerc.getText().toString());
persons = Double.parseDouble(etPers.getText().toString());