java - 我的情况无法正常工作我的应用程序在单击按钮时崩溃
问题描述
我正在尝试检查 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)
解决方案
您正在尝试将空字符串解析为浮点数,但失败了。
如果您想检查空值、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");
}
}
推荐阅读
- netsuite - 通过传递国家代码获取 NetSuite SuiteScript 2.0 中国家列表的内部 ID
- php - 使用 FOR 循环动态显示 DIV 内的内容
- docker - 找不到源路径也不知道docker
- excel - 在 Excel 中从日期格式的 MM/DD/YYYY HH:MM:SS.000 获取毫秒数
- shell - 每次用不同的参数编译一个fortran90文件
- r - 当有许多等于异常值的值时,如何在箱线图中标记“异常值”?
- ffmpeg - 如何使用 mpdecimate 过滤器从 00:00:00,00 到 00:00:00,25 部分删除重复的帧?
- angular - 无法将文件输入到 FileList angular4
- multithreading - Android Studio - AlertDialog 按钮监听器和 ProgressBar 视图
- python-3.x - tkinter 只显示标签文本的顶部