将空字符串转换为整数

问题描述 投票:14回答:7

是否有任何方法可以将null转换为Integer。 null实际上是一个字符串,我在我的服务层中传递该字符串,将其接受为整数。因此,每当我尝试将null字符串强制转换为Integer时,都会引发异常。但是我必须将null转换为Integer。

java casting
7个回答
23
投票

无法从String转换为Integer。但是,如果您尝试将字符串转换为整数,并且必须提供用于处理null字符串的实现,请查看以下代码片段:

String str = "...";
// suppose str becomes null after some operation(s).
int number = 0;
try
{
    if(str != null)
      number = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
    number = 0;
}

13
投票

如果您使用的是apache commons,则可以使用一种帮助方法来达到目的:

NumberUtils.createInteger(myString)

documentation中所述:

“将String转换为Integer,处理十六进制和八进制表示法;如果字符串为null,则返回null;如果无法转换该值,则抛出NumberFormatException


6
投票
String s= "";  
int i=0;
i=Integer.parseInt(s+0);
System.out.println(i);

尝试一下


3
投票

您不能从String转换为Integer。Java数据类型有两种:primitivereference。基本类型为:byte,short,int,long,char,float,double。引用类型为:类,接口,数组。byte-> short-> int-> long-> float-> double。是允许的,或者强制类型转换可以是其自身类型或其子类或超类类型或接口之一。所以这是前。功能一览

    public int getInteger(String no) {
    if (no != null) {
        return Integer.parseInt(no); //convert your string into integer 
    } else {
        return 0; // or what you want to return if string is Null
    }
}

2
投票

这呢?

private static void castTest() {
    System.out.println(getInteger(null));
    System.out.println(getInteger("003"));
    int a = getInteger("55");
    System.out.println(a);
}

private static Integer getInteger(String str) {
    if (str == null) {
        return new Integer(0);
    } else {
        return Integer.parseInt(str);
    }
}

1
投票

如果字符串为空,请尝试以下code:application将返回0,否则,如果字符串仅包含数字,则它将解析为int

代码:

(str.equals("null")?0:Integer.parseInt(str))

0
投票

如果您确定只需要处理空值,

int i=0;
i=(str==null?i:Integer.parseInt(str));
System.out.println(i);

对于非整数字符串,它将引发Numberformat异常

© www.soinside.com 2019 - 2024. All rights reserved.