java 如何使用默认值将 String 解析为 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45481560/
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
How can I parse String to int with the default value?
提问by Krunal
I need to parse a string user id into integer for that I used Integer.parseInt(String s)
but it returns null/nil, if there string has/holds non-decimal/integer value and in that case, I need to assign default integer value as 0
.
我需要将字符串用户 ID 解析为我使用的整数,Integer.parseInt(String s)
但它返回空/零,如果字符串具有/持有非十进制/整数值,在这种情况下,我需要将默认整数值分配为0
.
I tried this but it (? 0)
seems not working and I don't know whether it is correct syntax or not.
我试过这个,但它(? 0)
似乎不起作用,我不知道它的语法是否正确。
String userid = "user001";
int int_userid = Integer.parseInt(userid) ? 0;
How can assign default value to integer if there is null assignment?
如果有空分配,如何将默认值分配给整数?
String userid is a parameter argument as part of web service function call, so I cannot update it's data type to integer.
字符串 userid 是作为 Web 服务函数调用的一部分的参数参数,因此我无法将其数据类型更新为整数。
采纳答案by dev_kd
You can try this method with a regular expression.
你可以用正则表达式试试这个方法。
public static int parseWithDefault(String s, int defaultVal) {
return s.matches("-?\d+") ? Integer.parseInt(s) : defaultVal;
}
回答by msfoster
You're most likely using apache.commons.lang3 already:
您很可能已经在使用 apache.commons.lang3:
NumberUtils.toInt(str, 0);
回答by Yannick
That syntax won't work for Integer.parseInt()
, because it will result in a NumberFormatException
该语法不适用于Integer.parseInt()
,因为它会导致NumberFormatException
You could handle it like this:
你可以这样处理:
String userid = "user001";
int int_userid;
try {
int_userid = Integer.parseInt(userid);
} catch(NumberFormatException ex) {
int_userid = 0;
}
Please note that your variable names do not conform with the Java Code Convention
请注意您的变量名不符合 Java 代码约定
A better solution would be to create an own methodfor this, because I'm sure that you will need it more than once:
更好的解决方案是为此创建一个自己的方法,因为我相信您将不止一次需要它:
public static int parseToInt(String stringToParse, int defaultValue) {
try {
return Integer.parseInt(stringToParse);
} catch(NumberFormatException ex) {
return defaultValue; //Use default value if parsing failed
}
}
Then you simply use this method like for e.g.:
然后您只需使用此方法,例如:
int myParsedInt = parseToInt("user001", 0);
This call returns the default value 0
, because "user001" can't be parsed.
此调用返回默认值0
,因为无法解析“user001”。
If you remove "user" from the string and call the method...
如果您从字符串中删除“用户”并调用该方法...
int myParsedInt = parseToInt("001", 0);
…then the parse will be successful and return 1
since an int can't have leading zeros!
...然后解析将成功并返回,1
因为 int 不能有前导零!
回答by mgyongyosi
It might be a little over-engineering, but you can use Guava's Ints.tryParse(String)
with Java 8's Optionals like this:
这可能有点过度设计,但是您可以Ints.tryParse(String)
像这样将 Guava与 Java 8 的 Optionals 一起使用:
int userId = Optional.ofNullable(Ints.tryParse("userid001")).orElse(0)
回答by YCF_L
You can use this way with String::matches
like this :
您可以String::matches
像这样使用这种方式:
String userid = "user001";
int int_userid = userid.matches("\d+") ? Integer.parseInt(userid) : 0;
You ca also use -?\d+
for both positive and negative values :
您还可以使用-?\d+
正值和负值:
int int_userid = userid.matches("-?\d+") ? Integer.parseInt(userid) : 0;
回答by xenteros
I believe that you can achieve what you want by the following method:
我相信您可以通过以下方法实现您想要的:
public static int parseIntWithDefault(String s, int default) {
try {
return Integer.parseInt(s);
} catch(NumberFormatException e) {
return default;
}
}
and now just assign:
现在只需分配:
int int_userid = parseIntWithDefault(userId, 0);
Please have in mind, that using Java
one should use Java good practices about formatting the code. int_userid
is definitely something to improve.
请记住,使用Java
一个应该使用关于格式化代码的 Java 良好实践。int_userid
绝对是需要改进的地方。
回答by xoX Zeus Xox
String userid = "user001";
int int_userid = Integer.parseInt(userid) != null ? Integer.parseInt(userid) : 0);
Did you mean this syntax?
But since an int
can never be null
you have to instead do:
你是说这个语法吗?但是因为int
永远不可能是null
你必须做的:
String userid = "user001";
int int_userid;
try {
int_userid= Integer.parseInt(userid);
} catch (NumberFormatexception e) {
int_userid = 0;
}
回答by deepakl
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
}