简体   繁体   English

引起:java.lang.NumberFormatException:空字符串

[英]Caused by: java.lang.NumberFormatException: empty String

this is my calculator app when we normally click on equals button without add any calculation, that time app is crashing on this code这是我的计算器应用程序,当我们通常单击等于按钮而不添加任何计算时,应用程序在此代码上崩溃

 case R.id.equal:
            int item1=s1.getSelectedItemPosition();
            int item2=s2.getSelectedItemPosition();
            double value1=Double.parseDouble(e1.getText().toString());
            double result=evaluate(item1,item2,value1);
            e2.setText(result+"");
            break;

App is crashing on 3rd line应用程序在第三行崩溃

You can't parse to double if you have an empty string, The string you're trying to parse as double is empty.如果您有一个空字符串,则无法解析为双精度,您尝试解析为双精度的字符串为空。 You need to check if the getText() method returns a non-empty string before trying to do the parsing.在尝试进行解析之前,您需要检查getText()方法是否返回非空字符串。

case R.id.equal:
    int item1=s1.getSelectedItemPosition();
    int item2=s2.getSelectedItemPosition();
    double value1=ParseDouble(e1.getText().toString());
    double result=evaluate(item1,item2,value1);
    e2.setText(result+"");
    break;

double ParseDouble(String strNumber) {
    if (strNumber != null && strNumber.length() > 0) {
        try {
            return Double.parseDouble(strNumber);
            } 
        catch(Exception e) {
            return -1;   // or a default value to mark this field is wrong.
            }
        }
    else return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM