異常例題1

967 ワード


1, parse , 0-9 / a-f / A-F

public class ParseInt {
public static int parse(String s) {
int result = 0;
for (int i = 0; i < s.length(); ++i) {
char digit = s.charAt(i);//
if ('0' <= digit && digit <= '9') {
int d = digit - '0';
result = result * 16 + d;
} else if ('a' <= digit && digit <= 'f') {
int d = digit - 'a' + 10;
result = result * 16 + d;
} else if ('A' <= digit && digit <= 'F') {
int d = digit - 'A' + 10;
result = result * 16 + d;
} else {
throw new NumberFormatException(s + ":" + digit);
}
}
return result;
}

public static void main(String[] args) {
String s = "7f";
System.out.println(parse(s));
}