【问题标题】:What is the best way to make sure a String can be stored as an int in java确保 String 可以在 java 中存储为 int 的最佳方法是什么
【发布时间】:2012-06-19 14:19:01
【问题描述】:

我正在制作一个基于 Web 的应用程序,并且我有文本字段,其中的值存储为字符串。问题是某些文本字段将被解析为整数,并且您可以在字符串中存储比在整数中更大的数字。我的问题是,确保可以将 String 数字解析为 int 而不会出错的最佳方法是什么。

【问题讨论】:

  • 通过在 try/catch(NumberFormatException e) 中解析 Integer.parseInt(...) 来验证输入。
  • 你的号码有多大?你的数字是否超出了 Java 中可用类型的范围(双/浮点)?
  • @HovercraftFullOfEels 我不认为 OP 在谈论 NumberFormatException。我认为是关于String 转换为数字时(Integer),可能超出范围。
  • @KazekageGaara Integer.parseInt 检查范围
  • 除非您真的关心意外的前导或尾随空格,否则请在调用 parseInt() 之前在字符串上调用 String.trim(),如所有答案中所建议的那样。至少在 Java 6 中,parseInt() 在前导或尾随空格上抛出异常。

标签: java string parseint


【解决方案1】:

您可以为此使用 try/catch 结构。

try {
    Integer.parseInt(yourString);
    //new BigInteger(yourString);
    //Use the above if parsing amounts beyond the range of an Integer.
} catch (NumberFormatException e) {
    /* Fix the problem */
}

【讨论】:

    【解决方案2】:

    Integer.parseInt 方法检查 javadoc 明确说明的范围:

    An exception of type NumberFormatException is thrown if any of the following situations occurs:
    The first argument is null or is a string of length zero.
    The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
    Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
    The value represented by the string is not a value of type int.
    Examples:
     parseInt("0", 10) returns 0
     parseInt("473", 10) returns 473
     parseInt("-0", 10) returns 0
     parseInt("-FF", 16) returns -255
     parseInt("1100110", 2) returns 102
     parseInt("2147483647", 10) returns 2147483647
     parseInt("-2147483648", 10) returns -2147483648
     parseInt("2147483648", 10) throws a NumberFormatException
     parseInt("99", 8) throws a NumberFormatException
     parseInt("Kona", 10) throws a NumberFormatException
     parseInt("Kona", 27) returns 411787
    

    所以正确的方法是尝试解析字符串:

    try {
        Integer.parseInt(str);
    } catch (NumberFormatException e) {
        // not an int
    }
    

    【讨论】:

      【解决方案3】:

      将字符串解析为 BigInteger 而不是常规 Integer。这可以保持更高的值。

      BigInteger theInteger = new BigInteger(stringToBeParsed);
      

      【讨论】:

      • 不过,这似乎无法回答问题。
      • @dystroy。其实我觉得可以。我阅读问题的方式是他希望用户能够输入任何数字,但不希望程序由于数字太大而崩溃
      • 事实上也许。在问题中使用“int”而不是“integer”将是一个错误。
      【解决方案4】:

      您可以检查您的代码:

      • 将字符串转换为长字符串。
      • 将 long 值与整数(Integer 类中的常量)的最大值进行比较。
      • 如果 long 大于它,你就知道它不能被解析成 int 而不溢出。
      • 如果小于或等于它,请将 long 转换为 int。

      【讨论】:

      • 为什么不直接把它转换成int?
      • 因为我很傻,很明显。 (int 不会溢出到负值或失败吗?它需要一个 try/catch 块,这无疑是更好的答案。)
      【解决方案5】:

      始终解析 try catch 块中的字符串,因此如果发生任何异常或错误,您就知道 String to int 解析中存在一些错误。

      【讨论】:

        【解决方案6】:

        你可以使用Apache Commons Lang

        import org.apache.commons.lang.math.NumberUtils;
        
        NumberUtils.toInt( "", 10 );   // returns 10
        NumberUtils.toInt( null, 10 ); // returns 10
        NumberUtils.toInt( "1", 0 );  // returns 1
        

        如果字符串不是数值,则第二个数字是默认值。第一个参数是您要转换的字符串。

        对于大量数据,我会执行以下操作

        BigInteger val = null;
        try {
          val = new BigInteger( "1" );
        } catch ( NumberFormatException e ) {
          val = BigInteger.ZERO;
        }
        

        【讨论】:

          【解决方案7】:

          这个呢?

          BigInteger bigInt = BigInteger(numberAsString);
          boolean fitsInInt = ( bigInt.compareTo( BigInteger.valueOf(bigInt.intValue()) ) == 0;
          

          【讨论】:

            猜你喜欢
            • 2020-02-18
            • 2022-01-09
            • 2019-10-21
            • 1970-01-01
            • 2021-02-09
            • 2015-07-13
            • 2013-02-15
            • 2021-11-02
            • 1970-01-01
            相关资源
            最近更新 更多