android数字格式异常 [英] android number format exception
问题描述
我收到以下异常
java.lang.NumberFormatException:无效的int:"
java.lang.NumberFormatException: Invalid int: ""
当您尝试将值存储到共享首选项中而未在输入字段中插入任何内容时,就会发生这种情况.这是因为我将输入解析为一个整数(因为我需要对数字进行减法运算)
It is happening when you try to store a value into shared preferences whilst nothing has been inserted into the input field. This is because i am parsing the input as an int (as i need to do a subtraction with the figure)
这不是什么大问题,因为该应用程序可以运行,但是只是万一使用该应用程序的人想要烦恼并尝试按保存按钮而不输入任何我不想插入的数据.
This isn't much of a problem as the app will work however just incase someone using the app wants to be wierd and try and press the save button without entering any data I dont want it to insert.
我尝试了以下方法:
else if (obj ==null || obj.currentWeight.contains("")||obj.targetWeight.contains("")){
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setTitle("No Data Stored");
builder.setMessage("Please insert your target weight and your current weight and click Store Weight")
.setPositiveButton("OK", null).show();
根据我的判断,如果我保留上述声明为
From what i could make out if i kept the above statement as
else if (obj ==null){
然后,如果插入了null,则对话框将打开并显示一条消息.
then if a null is inserted the dialog would open and display a message.
我得到数字格式异常.
任何帮助将不胜感激
推荐答案
通常来说,异常处理是一种处理此类不良行为的好方法:
Generally speaking, exception processing is a good approach for this kind of undesired behavior :
if( obj != null && obj.getTargetWeight() != null ) {
try {
int i = Integer.parseInt( obj.getTargetWeight() );
//do something if target weight is a number
} catch( NumberFormatException ex ) {
//do something if target weight was not a number.
}
}
-编辑为精确的异常类型
---edited to precise exception type
这篇关于android数字格式异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!