[英]Setting an integer value in textView shows null, How to solve this in android?
[英]Setting null value to integer
我如何最初将 null 设置为整数变量而不是“0”。 我已经知道默认情况下所有 int 值都是“0”。 我使用了String.valueOf()
方法等。我不想打印为“null”。 我想像“”一样打印空白。 我得到数字格式异常。 请给出一个解决方案。
提前致谢
这是代码
public class IntegerDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String id="";
System.out.println(""+Integer.parseInt(id));
}
}
我相信你把问题复杂化了,这是一件非常简单的事情。 检查下面的代码:
Integer i = null;
System.out.println(i == null ?"":i);
您必须坚持使用java.lang.Integer
类。
String id = ""
Integer test = null;
if (!"".equals(id))
{
test = Integer.parseInt(id);
}
创建一个主值为null
的Integer
实例是没有意义的,但你可以在声明时这样做:
Integer id = null;
文档中列出了您收到NumberFormatException
的原因:
如果发生以下任何一种情况,则会抛出 NumberFormatException 类型的异常:
第一个参数为 null 或长度为零的字符串。
基数小于 Character.MIN_RADIX 或大于 Character.MAX_RADIX。
字符串的任何字符都不是指定基数的数字,除了第一个 > 字符可以是减号 '-' ('\-') 或加号 '+' ('\+') 前提是字符串比长度 1 长。
字符串表示的值不是 int 类型的值。
你不能调用Integer.parseInt("")
或Integer.parseInt(null)
,有这个限制。
如果您将null
或blank
解析为 int 它将抛出numberFormatException
。 在解析之前检查:
try{
System.out.println(StringUtils.isNotBlank(id)?Integer.parseInt(id):"");
}
catch(NumberFormatException e){
System.out.println("Not A Number");
}
还要通过捕获异常来确定字符串是否没有数字。 StringUtils.isNotBlank()
将检查null
和blank
。
除了解析,我们可以使用Integer.valueOf(null);
Integer int = null;
int 是基元,它们的默认值与 null 不同。
简单的盒装整数Integer i = null;
已经提供。 这是一个替代方案:
class NullableInt {
private int value;
private boolean isNull;
public NullableInt() { isNull = true; }
public NullableInt(int value) {
this.value = value;
isNull = false;
}
public NullableInt(String intRep) {
try { value = Integer.parseInt(intRep);
} catch (NumberFormatException) {
isNull = true;
}
}
boolean isNull() { return isNull; }
void setNull(boolean toNull) { isNull = toNull; }
void setValue(int value) { this.value = value; }
int getValue() { return value; }
@Override
public String toString() { return isNull ? "" : value; }
}
NullableInt integer1 = new NullableInt(56);
NullableInt integer2 = new NullableInt();
System.out.pritnln(integer1); // >> "56"
System.out.println(integer2); // >> ""
// and finally, to address the actual question:
String id = "";
System.out.println(new NullableInt(id)); // >> ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.