java是否具有不会为错误数据引发异常的int.tryparse? [英] Does java have a int.tryparse that doesn't throw an exception for bad data?

查看:360
本文介绍了java是否具有不会为错误数据引发异常的int.tryparse?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Java:封装Integer.parseInt()的好方法
如何转换要浮动的字符串,并避免在Java中使用try/catch?

Possible Duplicate:
Java: Good way to encapsulate Integer.parseInt()
how to convert a string to float and avoid using try/catch in java?

C#具有Int.TryParse: Int32.TryParse方法(字符串,Int32%)

C# has Int.TryParse: Int32.TryParse Method (String, Int32%)

此方法的优点在于,它不会为不良数据引发异常.

The great thing with this method is that it doesn't throw an exception for bad data.

在Java中,Integer.parseInt("abc")将引发异常,并且在这种情况下,很多性能将受到损害.

In java, Integer.parseInt("abc") will throw an exception, and in cases where this may happen a lot performance will suffer.

对于那些性能存在问题的情况,是否可以通过某种方式解决?

Is there a way around this somehow for those cases where performance is an issue?

我唯一想到的另一种方法是针对正则表达式运行输入,但是我必须进行测试以了解更快的方法.

The only other way I can think of is to run the input against an regex, but I have to test to see what is faster.

推荐答案

否.您必须这样制作自己的:

No. You have to make your own like this:

boolean tryParseInt(String value) {  
     try {  
         Integer.parseInt(value);  
         return true;  
      } catch (NumberFormatException e) {  
         return false;  
      }  
}

...,您可以像这样使用它:

...and you can use it like this:

if (tryParseInt(input)) {  
   Integer.parseInt(input);  // We now know that it's safe to parse
}

编辑(基于@Erk的评论)

EDIT (Based on the comment by @Erk)

如下所示应该会更好

public int tryParse(String value, int defaultVal) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return defaultVal;
    }
}

当您使用单个字符串参数方法重载此参数时,效果会更好,它将启用默认值为可选的使用.

When you overload this with a single string parameter method, it would be even better, which will enable using with the default value being optional.

public int tryParse(String value) {
    return tryParse(value, 0)
}

这篇关于java是否具有不会为错误数据引发异常的int.tryparse?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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