简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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