我使用以下方法将字符串更改为double,但不幸的是,这会关闭应用程序。 EditText输入类型是“NumberDecimal”
numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);
//App forceclose here. Not sure why.
final Double a = Double.parseDouble(numA.getText().toString());
final Double b = Double.parseDouble(numB.getText().toString());
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
}
});
答案 0 :(得分:4)
执行此检查:
if (!numA.getText().toString().equals("")) {
final Double a = Double.parseDouble(numA.getText().toString());
}
if (!numB.getText().toString().equals("")) {
final Double b = Double.parseDouble(numB.getText().toString());
}
Double.parseDouble()的空字符串参数产生NumberFormatException
。
作为建议,如果您正在制作计算器(或转换器),则应为无效输入添加更多检查。例如,您应该添加一个检查,以便用户何时输入小数点(。)或表单输入(3.)。
答案 1 :(得分:3)
试试这个;
String s = b.getText().toString();
final double a = Double.valueOf(s.trim()).doubleValue();
答案 2 :(得分:0)
您可能希望使用try catch,因为其他不可解析的数据会引发异常,并且最好只依靠UI来强制使用有效数字。
numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);
Double a;
Double b;
try {
a = Double.parseDouble(numA.getText().toString());
b = Double.parseDouble(numB.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
a = 0.0;
b = 0.0;
}
final double aFin = a;
final double bFin = b;
calculate.setOnClickListener(new View.OnClickListener() {
//Also, you used your class as an onClickListener you would have to make your doubles final.
@Override
public void onClick(View v) {
numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
//Division by zero will produce a NaN you should probably check user input data sanity
}
});