我有很多收集用户输入并解析它的代码, 我想解析整数值而不引发异常。
我当前的tryParseInt()
功能是代码很简单:
public static Integer tryParseInt( String text )
{
if(text == null)
return null;
try
{
return new Integer( text.trim() );
}
catch ( NumberFormatException e )
{
return null;
}
}
但是我得到了很多NumberFormatExceptions
我很担心,因为这可能会影响我的应用程序性能。
谁能建议我解析用户输入的最佳实践。
谢谢
最佳答案
您可以使用正则表达式,因为它更能防止失败
public static Integer tryParseInt(String text) {
if (text != null && !text.isEmpty()) {
if (text.trim().matches("[0-9]+")) {
return Integer.valueOf(text.trim());
}
}
return null;
}
关于Java tryParseInt 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31202879/