异常例题1

 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));
}

你可能感兴趣的:(异常)