我需要将字符串用户id解析为整数,因为我使用了Integer.parseInt(String s)
但它返回null / nil,如果字符串有/保持非十进制/整数值,那么我需要分配默认整数值为0
。
我尝试了这个,但它(? 0)
似乎不起作用,我不知道它是否是正确的语法。
String userid = "user001";
int int_userid = Integer.parseInt(userid) ? 0;
如果有空赋值,如何将默认值赋给整数?
String userid是一个参数参数,作为Web服务函数调用的一部分,因此我无法将其数据类型更新为整数。
答案 0 :(得分:10)
该语法不适用于Integer.parseInt()
,因为它会产生NumberFormatException
你可以这样处理:
String userid = "user001";
int int_userid;
try
{
int_userid = Integer.parseInt(userid);
}
catch(NumberFormatException ex)
{
int_userid = 0;
}
请注意,您的变量名称不符合Java Code Convention
更好的解决方案是为此创建一个自己的方法,因为我确信您需要多次:
public static int parseToInt(String stringToParse, int defaultValue)
{
int ret;
try
{
ret = Integer.parseInt(stringToParse);
}
catch(NumberFormatException ex)
{
ret = defaultValue; //Use default value if parsing failed
}
return ret;
}
然后您只需使用此方法,例如:
int myParsedInt = parseToInt("user001", 0);
此调用返回默认值0
,因为无法解析“user001”。
如果从字符串中删除“user”并调用方法...
int myParsedInt = parseToInt("001", 0);
...然后解析将成功并返回1
,因为int不能有前导零!
答案 1 :(得分:6)
您可以像String::matches
这样使用这种方式:
String userid = "user001";
int int_userid = userid.matches("\\d+") ? Integer.parseInt(userid) : 0;
您还可以将-?\d+
用于正值和负值:
int int_userid = userid.matches("-?\\d+") ? Integer.parseInt(userid) : 0;
答案 2 :(得分:6)
您最有可能使用apache.commons.lang3:
NumberUtils.toInt(str, 0);
答案 3 :(得分:4)
这可能有点过度工程,但您可以将Guava的Ints.tryParse(String)
与Java 8的Optionals一起使用,如下所示:
int userId = Optional.ofNullable(Ints.tryParse("userid001")).orElse(0)
答案 4 :(得分:2)
我相信你可以通过以下方法达到你想要的效果:
int int_userid = parseIntWithDefault(userId, 0);
现在只需分配:
Java
请记住,使用int_userid
使用Java良好做法来格式化代码。 f
绝对值得改进。
答案 5 :(得分:2)
您可以使用正则表达式尝试此方法。
public static int parseWithDefault(String s, int defaultVal) {
return s.matches("-?\\d+") ? Integer.parseInt(s) : defaultVal;
}
答案 6 :(得分:0)
String userid = "user001";
int int_userid = Integer.parseInt(userid) != null ? Integer.parseInt(userid) : 0);
你的意思是这个语法吗?
但由于int
永远不能null
,您必须改为:
String userid = "user001";
int int_userid;
try {
int_userid= Integer.parseInt(userid);
} catch (NumberFormatexception e) {
int_userid = 0;
}
答案 7 :(得分:-2)
int int_userid;
try {
int_userid = Integer.parseInt(userid); // try to parse the given user id
} catch (Exception e) { // catch if any exception
int_userid = 0; // if exception assign a default value
}