1.判断字符串是否为空;
2.判断字符串是否为空字符串;
3.判断是否为负数;
4.从左向右循环取字符,转化为数字,将上次结果乘10,加上当前数字;
5.在运算前,判断结果是否超出int型范围。
MyParseInt.java:
01.import java.util.*;
02.public class MyParseInt {
03.
04. public static int myParseInt(String str) throws NumberFormatException {
05. //存放结果
06. int result = 0;
07. //标记是否为负数
08. boolean negative = false;
09. //数字开始位置:正数为0,负数为1(除去‘-’)
10. int start = 0;
11. //int型边界值的十位以上的数字
12. int limitLeft;
13. //int型边界值的个位数字
14. int limitRight;
15. //判断是否为空
16. if (str == null) {
17. throw new NumberFormatException("null");
18. }
19. int len = str.length();
20. //判断是否为空字符串
21. if (len < 1) {
22. throw new NumberFormatException("empty");
23. } else {
24. if (str.charAt(0) == '-') {
25. if (len > 1) {
26. //负数
27. negative = true;
28. start = 1;
29. limitLeft = -(Integer.MIN_VALUE / 10);
30. limitRight = -(Integer.MIN_VALUE % 10);
31. } else {
32. throw new NumberFormatException("not number");
33. }
34. } else {
35. limitLeft = Integer.MAX_VALUE / 10;
36. limitRight = Integer.MAX_VALUE % 10;
37. }
38. }
39. //从左向右取字符,转化为数字,将上次结果乘10,加上当前数字
40. for (int i = start; i < len; i++) {
41. char c = str.charAt(i);
42. //判断是否为数字
43. if (c < 48 || c > 57) {
44. throw new NumberFormatException("not number");
45. } else {
46. int value = c - 48;//减去0的Ascii码 (从左向右依次取)47. //在运算前,判断结果是否超出int型范围
48. if (result > limitLeft || (result == limitLeft && value >= limitRight + 1)) {
49. throw new NumberFormatException("number is out of bounds");
50. } else {
51. result = result *10 + value;
52. }
53. }
54. }
55. if (negative) {
56. result = -result;
57. }
58. return result;
59. }
60.
61. public static void main(String[] args) {
62. while (true) {
63. Scanner sc = new Scanner(System.in);
64. String str = sc.next();
65. try {
66. System.out.println(MyParseInt.myParseInt(str));
67. }
68. catch (NumberFormatException e) {
69. e.printStackTrace();
70. }
71. }
72. }
73.}