方法 public static int parseInt(String str) 和 public static int parseInt(String str, int redix)
它是如何工作的?
& 他们之间有什么区别?
方法 public static int parseInt(String str) 和 public static int parseInt(String str, int redix)
它是如何工作的?
& 他们之间有什么区别?
哦,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);
}
它们的功能基本相同。 parseInt(String str)
假设 base-10(除非字符串以0x
or开头0
)。 parseInt(String str, int radix)
使用给定的基础。我没有看过代码,但我敢打赌第一个简单的调用parseInt(str, 10)
(除了在这两种特殊情况下它会使用16
and 8
)。