Java 将空值设置为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18544638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:55:07  来源:igfitidea点击:

Setting null value to integer

javastring

提问by Vijay Kumar

How can i set null to integer variable initially instead of "0". I know already by default all int value is "0". I used String.valueOf()method etc. I dont want to print as "null". I want to print blank like " ". I get number format exception. Please give one solution for that.

我如何最初将 null 设置为整数变量而不是“0”。我已经知道默认情况下所有 int 值都是“0”。我使用了String.valueOf()方法等。我不想打印为“null”。我想像“”一样打印空白。我得到数字格式异常。请给出一个解决方案。

Thanks in advance

提前致谢

Here is the code

这是代码

public class IntegerDemo {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String id="";


        System.out.println(""+Integer.parseInt(id));

    }
}

采纳答案by dharam

I am sure you are over-complicating the problem, it is a real simple thing to do. Check the code below:

我相信你把问题复杂化了,这是一件非常简单的事情。检查下面的代码:

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

回答by Suresh Atta

Use Integerwrapper class instead of primitive

使用 整数包装类而不是原始类

Integer myInt= null;

For object references you can set null.But you cannot to primitives.

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

回答by inteloid

Integer int = null;

ints are primitives, they have default values different from null.

int 是基元,它们的默认值与 null 不同。

回答by ced-b

You would have to stick with the java.lang.Integerclass.

你必须坚持java.lang.Integer上课。

String id = ""
Integer test = null;

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

回答by Makoto

Creating an instance of Integerwith its primary value as nullis meaningless, but you can do this on declaration:

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

Integer id = null;

The reason you're getting NumberFormatExceptionis laid out in the documentation:

你得到的原因在文档中NumberFormatException列出:

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.

  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.

  • Any character of the string is not a digit of the specified radix, except that the first > character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.

  • The value represented by the string is not a value of type int.

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

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

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

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

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

You can't call Integer.parseInt("")or Integer.parseInt(null), with that limitation.

你不能调用Integer.parseInt("")or Integer.parseInt(null),有这个限制。

回答by azz

The simple boxed Integer Integer i = null;has already been supplied. Here is an alternative:

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)); // >> ""

回答by commit

If you parse nullor blankas int it will throw numberFormatException. Check for that before parsing:

如果您解析nullblank作为 int 它将抛出numberFormatException. 在解析之前检查:

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

Also be sure if string has not number by catching exception. StringUtils.isNotBlank()will check for both nullas well as blank.

还要通过捕获异常来确定字符串是否没有数字。StringUtils.isNotBlank()将检查两者null以及blank.