-2

方法 public static int parseInt(String str) 和 public static int parseInt(String str, int redix)

它是如何工作的?

& 他们之间有什么区别?

4

3 回答 3

4

您可以在此处阅读实现。以及这里的文档。

至于区别:

第一个假设字符串是十进制表示,而第二个期望另一个参数是表示的基础(二进制、十六进制、十进制等)

parseInt(String str)实现为 return parseInt(str, 10)

于 2012-05-04T13:29:19.713 回答
2

哦,java,它开源有多好。来自JDK6中的整数:

 /**
 * Parses the specified string as a signed decimal integer value. The ASCII
 * character \u002d ('-') is recognized as the minus sign.
 *
 * @param string
 *            the string representation of an integer value.
 * @return the primitive integer value represented by {@code string}.
 * @throws NumberFormatException
 *             if {@code string} cannot be parsed as an integer value.
 */
public static int parseInt(String string) throws NumberFormatException {
    return parseInt(string, 10);
}

并带有基数:

/**
 * Parses the specified string as a signed integer value using the specified
 * radix. The ASCII character \u002d ('-') is recognized as the minus sign.
 *
 * @param string
 *            the string representation of an integer value.
 * @param radix
 *            the radix to use when parsing.
 * @return the primitive integer value represented by {@code string} using
 *         {@code radix}.
 * @throws NumberFormatException
 *             if {@code string} cannot be parsed as an integer value,
 *             or {@code radix < Character.MIN_RADIX ||
 *             radix > Character.MAX_RADIX}.
 */
public static int parseInt(String string, int radix) throws NumberFormatException {
    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
        throw new NumberFormatException("Invalid radix: " + radix);
    }
    if (string == null) {
        throw invalidInt(string);
    }
    int length = string.length(), i = 0;
    if (length == 0) {
        throw invalidInt(string);
    }
    boolean negative = string.charAt(i) == '-';
    if (negative && ++i == length) {
        throw invalidInt(string);
    }

    return parse(string, i, radix, negative);
}
于 2012-05-04T13:32:15.653 回答
0

它们的功能基本相同。 parseInt(String str)假设 base-10(除非字符串以0xor开头0)。 parseInt(String str, int radix)使用给定的基础。我没有看过代码,但我敢打赌第一个简单的调用parseInt(str, 10)(除了在这两种特殊情况下它会使用16and 8)。

于 2012-05-04T13:29:43.247 回答