1

我使用以下方式将字符串更改为双精度,但不幸的是这会关闭应用程序。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)));
    }
});
4

3 回答 3

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.) 的输入。

于 2013-07-23T02:49:50.723 回答
3

尝试这个;

          String s = b.getText().toString();  
          final double a = Double.valueOf(s.trim()).doubleValue();
于 2013-07-23T02:44:19.570 回答
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
    }
});
于 2013-07-23T03:10:28.083 回答