handle negative numbers in Long.parseLong() and improve error detection

This commit is contained in:
Joel Dice 2007-08-23 20:35:27 -06:00
parent dd17a27485
commit 493667a6cc

View File

@ -99,18 +99,29 @@ public final class Long extends Number {
} }
public static long parseLong(String s, int radix) { public static long parseLong(String s, int radix) {
int i = 0;
long number = 0; long number = 0;
boolean negative = s.startsWith("-");
if (negative) {
i = 1;
}
for (int i = 0; i < s.length(); ++i) { for (; i < s.length(); ++i) {
char c = s.charAt(i); char c = s.charAt(i);
if (((c >= '0') && (c <= '9')) || if (((c >= '0') && (c <= '9')) ||
((c >= 'a') && (c <= 'z'))) { ((c >= 'a') && (c <= 'z'))) {
long digit = ((c >= '0' && c <= '9') ? (c - '0') : (c - 'a' + 10)); long digit = ((c >= '0' && c <= '9') ? (c - '0') : (c - 'a' + 10));
number += digit * pow(radix, (s.length() - i - 1)); if (digit < radix) {
} else { number += digit * pow(radix, (s.length() - i - 1));
throw new NumberFormatException("invalid character " + c + " code " + continue;
(int) c); }
} }
throw new NumberFormatException("invalid character " + c + " code " +
(int) c);
}
if (negative) {
number = -number;
} }
return number; return number;