我怎样才能解析字符串为int与默认值?
问题描述:
我需要解析一个字符串用户id到我使用的整数Integer.parseInt(String s)
但它返回null/nil,如果那里字符串有/保存非十进制/整数值,在这种情况下,我需要指定默认整数值为0
。我怎样才能解析字符串为int与默认值?
我试过了,但它(? 0)
似乎不工作,我不知道它是否是正确的语法。
String userid = "user001";
int int_userid = Integer.parseInt(userid) ? 0;
如果赋值为空,如何将默认值赋值为整数?
字符串用户ID是作为Web服务函数调用的一部分的参数参数,所以我无法将其数据类型更新为整数。
答
您可以使用正则表达式尝试此方法。
public static int parseWithDefault(String s, int default) {
return s.matches("-?\\d+") ? Integer.parseInt(s) : default;
}
答
这句法不会为Integer.parseInt()
工作,因为它会导致NumberFormatException
你可以处理它这样
String userid = "user001";
int int_userid;
try
{
int_userid = Integer.parseInt(userid);
}
catch(NumberFormatException p_ex)
{
int_userid = 0;
}
答
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
}
答
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;
}
答
您可以用这种方式与String::matches
这样的:
String userid = "user001";
int int_userid = userid.matches("\\d+") ? Integer.parseInt(userid) : 0;
也CA使用-?\d+
的正面和负面的价值观:
int int_userid = userid.matches("-?\\d+") ? Integer.parseInt(userid) : 0;
答
我相信你可以通过下面的m来实现你想要的ethod:
public static int parseIntWithDefault(String s, int default) {
try {
return Integer.parseInt(s);
} catch(NumberFormatException e) {
return default;
}
}
现在只分配:
int int_userid = parseIntWithDefault(userId, 0);
请有记住,使用Java
应该使用有关格式化代码的Java的良好做法。 int_userid
绝对是要改进的地方。
答
你最有可能使用apache.commons.lang3不已:
NumberUtils.toInt(str, 0);
答
这可能是有点过度工程,但你可以用番石榴的Ints.tryParse(String)
与Java 8的选配是这样的:
int userId = Optional.ofNullable(Ints.tryParse("userid001")).orElse(0)
您已经发明了Java中不存在的语法。如果parseInt不能解析字符串,则会抛出异常。你可以抓住例外来处理这种情况。 – khelwood
“,但它返回空,如果有字符串有非整数值”不,它不。一个int返回方法不能返回null。它引发一个异常。 – Michael
当您运行该程序时,您应该会在eclipse控制台中看到一个异常。 – deepakl