确保String可以作为int存储在java中的最佳方法是什么

use*_*793 7 java string parseint

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

Mic*_*ael 11

您可以使用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 */
}
Run Code Online (Sandbox Code Playgroud)


Den*_*ret 5

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
Run Code Online (Sandbox Code Playgroud)

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

try {
    Integer.parseInt(str);
} catch (NumberFormatException e) {
    // not an int
}
Run Code Online (Sandbox Code Playgroud)