将null值设置为整数

时间:2013-08-31 04:53:35

标签: java string

如何将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));

    }
}

8 个答案:

答案 0 :(得分:3)

使用Integer包装类而不是原始

Integer myInt= null;

对于对象引用,您可以设置null。但是不能primitives

答案 1 :(得分:3)

我确信你的问题过于复杂,这是一件非常简单的事情。检查以下代码:

Integer i = null;
System.out.println(i == null ?"":i);

答案 2 :(得分:0)

你必须坚持使用java.lang.Integer类。

String id = ""
Integer test = null;

if (!"".equals(id))
{
   test = Integer.parseInt(id);
}

答案 3 :(得分:0)

创建Integer的实例,其主要值为null是没有意义的,但您可以在声明时执行此操作:

Integer id = null;

您获得NumberFormatException的原因是in the documentation

  

如果发生以下任何一种情况,则抛出NumberFormatException类型的异常:

     
      
  • 第一个参数为null或为长度为零的字符串。

  •   
  • 基数小于Character.MIN_RADIX或大于Character.MAX_RADIX。

  •   
  • 字符串的任何字符都不是指定基数的数字,除了第一个>如果字符串长度超过长度1,则字符可以是减号' - '('\ u002D')或加号'+'('\ u002B')。

  •   
  • 字符串表示的值不是int类型的值。

  •   

您无法使用此限制来致电Integer.parseInt("")Integer.parseInt(null)

答案 4 :(得分:0)

如果您将nullblank解析为int,则会抛出numberFormatException。在解析之前检查:

try{
   System.out.println(StringUtils.isNotBlank(id)?Integer.parseInt(id):"");
}
catch(NumberFormatException e){
   System.out.println("Not A Number");
}

还要确保字符串是否通过捕获异常而没有编号。 StringUtils.isNotBlank()会同时检查nullblank

答案 5 :(得分:0)

我们可以使用Integer.valueOf(null);

代替解析

答案 6 :(得分:-1)

Integer int = null;

int是原语,它们的默认值与null不同。

答案 7 :(得分:-1)

已经提供了简单的盒装整数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)); // >> ""