简体   繁体   English

如何摆脱这个 NumberFormatException?

[英]How to get rid of this NumberFormatException?

I am developing a simple calculator app using Android Studio.我正在使用 Android Studio 开发一个简单的计算器应用程序。 It shows error at these lines,它在这些行显示错误,

      compute();
      value2 = Double.parseDouble(display.getText().toString());

Below is my android code:下面是我的安卓代码:

 sum.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            compute();
            act = ADD;
            display.setText(String.valueOf(value1) + "+");
          //  display.setText(display.getText().toString() + String.valueOf(value2));
           // display.setText(null);
        }
    });

when equal is pressed,当按下相等时,

equal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            compute();
            //act = EQU;
            //result.setText(display.getText().toString() + String.valueOf(value2) +  "=" + String.valueOf(value1));
           // result.setText(String.valueOf(value1));
         //   result.setText(display.getText().toString()+String.valueOf(value1));
         //   result.setText(String.valueOf(value1));
           //display.setText(null);
            result.setText(String.valueOf(result_num));
        }
    });

}

Here doing the calculation part这里做计算部分

    public void compute(){
        if(!Double.isNaN(value1)){
            value2 = Double.parseDouble(display.getText().toString());

            switch (act){
                case ADD:
                    result_num = value1 + value2;
                    //break;
                case SUB:
                    result_num = value1 - value2;
                    break;
                case MUL:
                    value1 = value1 * value2;
                    break;
                case DIV:
                    value1 = value1 / value2;
                    break;
               /* case EQU:
                    break;*/
            }
        }
        else{
            value1 = Double.parseDouble(display.getText().toString());
        }
    }
}

With this code, I couldn't proceed next step.使用此代码,我无法进行下一步。 Why this is not working?为什么这不起作用?

If you are parsing values like space, alphanumeric, special character you will get NumberFormatException .如果您正在解析空格、字母数字、特殊字符等值,您将得到NumberFormatException In your case you are concatenating "+" in onClick of sum at this line display.setText(String.valueOf(value1) + "+");在你的情况,你在这一行总和的onClick串联“+” display.setText(String.valueOf(value1) + "+"); and you are parsing that value here value2 = Double.parseDouble(display.getText().toString());你在这里解析那个值value2 = Double.parseDouble(display.getText().toString()); and here value1 = Double.parseDouble(display.getText().toString());这里value1 = Double.parseDouble(display.getText().toString()); in compute() method which will definitely cause NumberFormatException.compute()方法中肯定会导致 NumberFormatException。 So, split the value based on "+" and parse it.因此,根据“+”拆分值并解析它。

parseDouble can throw NumberFormatException and NullPointerException so you have to surround parseDouble with try/catch every time you are calling it or you have the risk to crash. parseDouble可以抛出NumberFormatExceptionNullPointerException,所以你必须在每次调用它时用 try/catch 包围 parseDouble 否则你有崩溃的风险。 Here is这是

/**
     * Returns a new {@code double} initialized to the value
     * represented by the specified {@code String}, as performed
     * by the {@code valueOf} method of class
     * {@code Double}.
     *
     * @param  s   the string to be parsed.
     * @return the {@code double} value represented by the string
     *         argument.
     * @throws NullPointerException  if the string is null
     * @throws NumberFormatException if the string does not contain
     *         a parsable {@code double}.
     * @see    java.lang.Double#valueOf(String)
     */
    public static double parseDouble(String s) throws NumberFormatException {
        return FloatingDecimal.parseDouble(s);
    }

so all of your parseDoubles should look like this (also you should trim your string to prevent passing spaces to parseDouble):所以你所有的 parseDouble 应该看起来像这样(你也应该修剪你的字符串以防止将空格传递给 parseDouble):

    try{
        value2 = Double.parseDouble(display.getText().toString().trim());
    }catch (NumberFormatException | NullPointerException ex){
        //set some value in case of exceptions
        //, for example, value2=0 or show a message to user cause his input is not valid
    }

Check what display.getText().toString() is returning.检查 display.getText().toString() 返回什么。 It should not return alphanumeric string or string with special characters.它不应返回字母数字字符串或带有特殊字符的字符串。 It should return a numeric string ie string with numbers only otherwise you will get NumberFormatException.它应该返回一个数字字符串,即只有数字的字符串,否则你会得到 NumberFormatException。

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

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