如何将String解析为默认值的int? [英] How can I parse String to int with the default value?

查看:159
本文介绍了如何将String解析为默认值的int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串用户ID解析为整数,因为我使用了 Integer.parseInt(String s),但是如果存在字符串/具有字符串,它将返回null / nil非小数/整数值,在这种情况下,我需要将默认整数值指定为 0

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.

I尝试过这个,但是它(?0)似乎不起作用,我不知道它是否正确。

I tried this but it (? 0) seems not working and I don't know whether it is correct syntax or not.

String userid = "user001";
int int_userid = Integer.parseInt(userid) ? 0;

如果没有空赋值,如何将默认值赋给整数?

How can assign default value to integer if there is null assignment?

字符串userid是Web服务函数调用中的参数参数,因此无法将其数据类型更新为整数。

String userid is a parameter argument as part of web service function call, so I cannot update it's data type to integer.

推荐答案

您可以使用正则表达式尝试此方法。

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;   
}

这篇关于如何将String解析为默认值的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆