[关闭]
@act262 2017-06-28T06:07:29.000000Z 字数 1364 阅读 754

Java Integer 使用问题

Java


使用Integer.parseInt方法

EditText文本框输入了纯整数字,然后将输入的文本转换为对应的金额数值

  1. String text = editText.getText().toString();
  2. int money = Integer.parseInt(text);

数值较小时没有问题,但是数字大于2ⁿ31 (Integer.MAX_VALUE = 2147483647)就会出现解析异常
i.e. 输入9999999999 总共10位数字,

解决方案

要么限定EditText的长度不能超过10位,或者不要大于2ⁿ31 ,或者用long类型来解析。

分析Integer的源码

  1. public static int parseInt(String string) throws NumberFormatException {
  2. return parseInt(string, 10);
  3. }
  4. public static int parseInt(String string, int radix) throws NumberFormatException {
  5. if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
  6. throw new NumberFormatException("Invalid radix: " + radix);
  7. }
  8. if (string == null || string.isEmpty()) {
  9. throw invalidInt(string);
  10. }
  11. char firstChar = string.charAt(0);
  12. int firstDigitIndex = (firstChar == '-' || firstChar == '+') ? 1 : 0;
  13. if (firstDigitIndex == string.length()) {
  14. throw invalidInt(string);
  15. }
  16. return parse(string, firstDigitIndex, radix, firstChar == '-');
  17. }
  18. // 解析数字的算法
  19. private static int parse(String string, int offset, int radix, boolean negative) throws NumberFormatException {
  20. int max = Integer.MIN_VALUE / radix;
  21. int result = 0;
  22. int length = string.length();
  23. while (offset < length) {
  24. int digit = Character.digit(string.charAt(offset++), radix);
  25. if (digit == -1) {
  26. throw invalidInt(string);
  27. }
  28. if (max > result) {
  29. throw invalidInt(string);
  30. }
  31. int next = result * radix - digit;
  32. if (next > result) {
  33. throw invalidInt(string);
  34. }
  35. result = next;
  36. }
  37. if (!negative) {
  38. result = -result;
  39. if (result < 0) {
  40. throw invalidInt(string);
  41. }
  42. }
  43. return result;
  44. }

因为int类型的范围是2ⁿ31,所以解析的范围不能超过最大值。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注