首页 > 解决方案 > 我的情况无法正常工作我的应用程序在单击按钮时崩溃

问题描述

我正在尝试检查 EidtText 是否为空。EditText 的变量是浮点类型。

float interObtain = Float.valueOf(editText1.getText().toString());
if (interObtain == 0 ) {
  editText1.setError("Please Fill this Field");
}

07-31 12:04:16.363 26780-26780/com.example.iubmeritcalculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.iubmeritcalculator, PID: 26780
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 java.lang.Float.valueOf(Float.java:343) at android.view.View.performClick(View.java:5052)at android.view.View$PerformClick.run(View.java:20162) at android.os.Handler.handleCallback(Handler.java:739)at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5753) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:145) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

标签: javaandroidnumberformatexception

解决方案


您正在尝试将空字符串解析为浮点数,但失败了。

如果您想检查空值、0 值或无效的格式值,您可以尝试:

   if (editText1.getText().isEmpty()) {
     editText1.setError("Please Fill this Field");
   } else {
     try{
       float interObtain = Float.valueOf(editText1.getText());
       if (interObtain == 0 ) {
         editText1.setError("Value should be different from 0");
       }
     } catch(NumberFormatException ex){
       editText1.setError("Value has an invalid format");
     }
   }

推荐阅读