/*** Parses the string argument as a signed integer in the radix
* specified by the second argument. The characters in the string
* must all be digits of the specified radix (as determined by
* whether {@linkjava.lang.Character#digit(char, int)} returns a
* nonnegative value), except that the first character may be an
* ASCII minus sign
'-'
(
'\u002D'
) to
* indicate a negative value. The resulting integer value is returned.
*
* 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
* {@linkjava.lang.Character#MIN_RADIX} or
* larger than {@linkjava.lang.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
*
*
*@params the
String
containing the integer
* representation to be parsed
*@paramradix the radix to be used while parsing
s
.
*@returnthe integer represented by the string argument in the
* specified radix.
*@exceptionNumberFormatException if the
String
* does not contain a parsable
int
.*/
public static int parseInt(String s, intradix)throwsNumberFormatException
{if (s == null) {throw new NumberFormatException("null");
}if (radix
" less than Character.MIN_RADIX");
}if (radix >Character.MAX_RADIX) {throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}int result = 0;boolean negative = false;int i = 0, max =s.length();intlimit;intmultmin;intdigit;if (max > 0) {if (s.charAt(0) == '-') {
negative= true;
limit=Integer.MIN_VALUE;
i++;
}else{
limit= -Integer.MAX_VALUE;
}
multmin= limit /radix;if (i
digit= Character.digit(s.charAt(i++),radix);if (digit < 0) {throwNumberFormatException.forInputString(s);
}else{
result= -digit;
}
}while (i
digit = Character.digit(s.charAt(i++),radix);if (digit < 0) {throwNumberFormatException.forInputString(s);
}if (result
}
result*=radix;if (result < limit +digit) {throwNumberFormatException.forInputString(s);
}
result-=digit;
}
}else{throwNumberFormatException.forInputString(s);
}if(negative) {if (i > 1) {returnresult;
}else {
throwNumberFormatException.forInputString(s);
}
}else{return -result;
}
}
public static int parseInt(String s) throwsNumberFormatException {return parseInt(s,10);
}