我有一个带有几个 EditTexts 的应用程序。用户留空,程序计算空变量。这是启动它的按钮的 onClickListener。我希望在切换之前完成所有解析,这样我只需要解析所有条目一次,然后为空条目输入 0,因为这会产生错误。
如何简化此代码?
public void buttonCalc() {
calc.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
pv = (EditText) getActivity().findViewById(R.id.pv_pv);
fv = (EditText) getActivity().findViewById(R.id.pv_fv);
r = (EditText) getActivity().findViewById(R.id.pv_r);
n = (EditText) getActivity().findViewById(R.id.pv_n);
t = (EditText) getActivity().findViewById(R.id.pv_t);
answer = (TextView) getActivity().findViewById(R.id.pv_answer);
//check for fields and choice
if (pv.getText().toString().equals("")) {emptyfields++;choice = 1;}
if (fv.getText().toString().equals("")) {emptyfields++;choice = 2;}
if (r.getText().toString().equals("")) {emptyfields++;choice = 3;}
if (n.getText().toString().equals("")) {emptyfields++;choice = 4;}
if (t.getText().toString().equals("")) {emptyfields++;choice = 5;}
if (emptyfields > 1) {MiscMethods.ErrorToast(1);}
else{
emptyfields--;
try {
} catch (Exception e) {
}
switch (choice) {
case 1:// pv
double fv1 = Double.parseDouble(fv.getText().toString());
double r1 = Double.parseDouble(r.getText().toString());
double n1 = Double.parseDouble(n.getText().toString());
double t1 = Double.parseDouble(t.getText().toString());
double result1 = fv1/(Math.pow(1+(r1/n1),n1*t1));
result1 = MiscMethods.rounder(result1, 2);
answer.setText(answer_pv + result1);
break;
case 2:// fv
double pv2 = Double.parseDouble(pv.getText().toString());
double r2 = Double.parseDouble(r.getText().toString());
double n2 = Double.parseDouble(n.getText().toString());
double t2 = Double.parseDouble(t.getText().toString());
double result2 = pv2*(Math.pow(1 + (r2 / n2), n2 * t2));
result2 = MiscMethods.rounder(result2, 2);
answer.setText(answer_fv + result2);
break;
case 3:// r
double pv3 = Double.parseDouble(pv.getText().toString());
double fv3 = Double.parseDouble(fv.getText().toString());
double n3 = Double.parseDouble(n.getText().toString());
double t3 = Double.parseDouble(t.getText().toString());
double result3 = ((Math.pow(fv3 / pv3, (1 / (n3 * t3)))) - 1)* n3;
result3 = MiscMethods.rounder(result3, 4);
answer.setText(answer_r +" "+ result3 + " / " + (result3*100)+"%");
break;
case 4:// n
MiscMethods.ErrorToast(2);
break;
case 5:// t
double pv5 = Double.parseDouble(pv.getText().toString());
double fv5 = Double.parseDouble(fv.getText().toString());
double n5 = Double.parseDouble(n.getText().toString());
double r5 = Double.parseDouble(r.getText().toString());
double result5 = (Math.log((fv5 / pv5))) / ((Math.log((1 + (r5 / n5)))) * n5);
result5 = MiscMethods.rounder(result5, 2);
answer.setText(answer_t +" "+ result5);
break;
default:
MiscMethods.ErrorToast(3);
break;
}// switch ends
}// else ends
}
});
}