H
H
hottabb2018-03-17 23:58:53
Android
hottabb, 2018-03-17 23:58:53

Why does NumberFormatException occur?

when you click on the calculation button - an error occurs and the application restarts, it has already broken its whole head, what could be the error?
THE CODE:

@Override
    public void onClick(View v) {
        float Per = 0;
        float Temp = 0;
        float result = 0;

        Per = Float.parseFloat(Peresushenie.getText().toString());
        Temp = Float.parseFloat(Temperatura.getText().toString());

        switch (v.getId()){
            case R.id.back:
                finish();
                sp.play(soundklick, 1, 1, 0, 0, 1);
                break;
            case R.id.rasschet:
                if (TextUtils.isEmpty(Peresushenie.getText().toString())
                        || TextUtils.isEmpty(Temperatura.getText().toString())) {
                    Toast toast = Toast.makeText(getApplicationContext(),
                            "Введите данные!", Toast.LENGTH_LONG);
                    toast.show();
                    break;
                }
                else {
                    oper = "*";
                    result = Per * Temp;
                    sp.play(soundklick, 1, 1, 0, 0, 1);
                    break;
                }

            default:
                break;
        }

Mistake:
03-17 23:54:20.234 4236-4236/com.hottabb.sugar.sugar_zavod E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hottabb.sugar.sugar_zavod, PID: 4236
java.lang.NumberFormatException: Invalid float: " "
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:308)
at java.lang.Float.parseFloat(Float.java:306)
at com.hottabb.sugar.sugar_zavod.RasschetActivity.onClick(RasschetActivity.java:70)
at android.view.View.performClick(View.java:5226)
at android.view.View$PerformClick.run(View.java:21350 )
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5571)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav, 2018-03-18
@hottabb

The Float.parseFloat() method may throw a NumberFormatException if you pass an invalid string there. In this case, you are passing an empty string there, which is not a valid number.
You should add handling of the given error or to check a line for emptiness. How to handle errors - you can read the documentation on the try catch statement

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question