@act262
2017-06-28T06:07:29.000000Z
字数 1364
阅读 877
Java
EditText文本框输入了纯整数字,然后将输入的文本转换为对应的金额数值
String text = editText.getText().toString();
int money = Integer.parseInt(text);
数值较小时没有问题,但是数字大于2ⁿ31 (Integer.MAX_VALUE = 2147483647)就会出现解析异常
i.e. 输入9999999999 总共10位数字,
要么限定EditText的长度不能超过10位,或者不要大于2ⁿ31 ,或者用long类型来解析。
public static int parseInt(String string) throws NumberFormatException {
return parseInt(string, 10);
}
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 || string.isEmpty()) {
throw invalidInt(string);
}
char firstChar = string.charAt(0);
int firstDigitIndex = (firstChar == '-' || firstChar == '+') ? 1 : 0;
if (firstDigitIndex == string.length()) {
throw invalidInt(string);
}
return parse(string, firstDigitIndex, radix, firstChar == '-');
}
// 解析数字的算法
private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException {
int max = Integer.MIN_VALUE / radix;
int result = 0;
int length = string.length();
while (offset < length) {
int digit = Character.digit(string.charAt(offset++), radix);
if (digit == -1) {
throw invalidInt(string);
}
if (max > result) {
throw invalidInt(string);
}
int next = result * radix - digit;
if (next > result) {
throw invalidInt(string);
}
result = next;
}
if (!negative) {
result = -result;
if (result < 0) {
throw invalidInt(string);
}
}
return result;
}
因为int类型的范围是2ⁿ31
,所以解析的范围不能超过最大值。