1.字符串转换成整数,字符串都是char字符组成 1).ACSII 码型数字 2).输入特殊字符NULL,@或者非数字的字符 3).字符串中有正负号
整体思路分为四部分:
1.判断字符串是不是空的,这里用字符串的长度显示
2).字符串中是否有空格
3).判断输入首字符是—,+,规定转换后整数是正数还是负数
4).只有数字型字符串才能转换,考虑是否发生溢出
1 package Heap; 2 3 public class StrToInteger { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 String S=" +1213"; 8 int Result=Atoi(S); 9 10 if(isNULL) 11 { 12 System.out.println("输入字符串NULL"); 13 } 14 else 15 { 16 if(ValidInput && !isOverFlow) 17 { 18 System.out.println(Result); 19 } 20 21 if(ValidInput==false) 22 { 23 System.out.println("输入字符串非法的"); 24 } 25 26 if(isOverFlow) 27 { 28 System.out.println("算法溢出"); 29 } 30 } 31 } 32 33 static boolean ValidInput=true;/*判断输入字符串是合理吗*/ 34 static boolean isOverFlow=false; 35 static boolean isNULL=false; 36 public static int Atoi(String Str) 37 { 38 int Sign=1,index=0;int result=0; 39 40 41 /*如果输入字符串是null,表示这个字符串长度为0*/ 42 43 if(Str.length()==0) 44 { 45 46 isNULL=true; 47 } 48 else 49 { 50 51 /*判断字符串是否合法输入或者是溢出*/ 52 while(index<Str.length()) 53 { 54 if(Str.charAt(index)==' ') 55 { 56 index++; 57 continue; 58 59 } 60 else 61 { 62 63 64 /*判断符号*/ 65 if(Str.charAt(index)=='+') 66 { 67 Sign=1; 68 index++; 69 70 } 71 else if(Str.charAt(index)=='-') 72 { 73 Sign=-1; 74 index++; 75 } 76 77 if(Str.charAt(index)<='9' && Str.charAt(index)>=0) 78 { 79 result=result*10+Str.charAt(index)-'0'; 80 81 /*防止输入的数发生溢出*/ 82 if(result>Integer.MAX_VALUE || result<Integer.MIN_VALUE) 83 { 84 System.out.println("输入数据发生溢出"); 85 isOverFlow=true; 86 break; 87 } 88 } 89 else 90 { 91 ValidInput=false; 92 System.out.println("输入字符串非法的"); 93 94 break; 95 96 } 97 } 98 99 index++; 100 } 101 } 102 103 return Sign*result; 104 } 105 106 }