Packagecom.test; Public classAtoitest { Public Static voidMain (string[] args)throwsException {String s= "-011134"; System.out.println ("String before conversion:" +s); System.out.println ("Atoi1 converted string:" +Atoi1 (s)); System.out.println ("Atoi2 converted string:" +Atoi2 (s)); } /*** Do not use Java built-in functions to convert string strings to numbers *@paramS *@return * @throwsException*/ Public Static intATOI1 (String s)throwsException {if(s = =NULL|| S.length () = = 0) { Throw NewException ("The string to be converted is empty and cannot be converted!") "); } intRetint = 0; int[] num =New int[S.length ()]; for(inti = 0; I < s.length (); i++) { Charc =S.charat (i); Switch(c) { Case‘-‘: Num[i]=-1; Break; Case' 0 ': Num[i]= 0; Break; Case' 1 ': Num[i]= 1; Break; Case' 2 ': Num[i]= 2; Break; Case' 3 ': Num[i]= 3; Break; Case' 4 ': Num[i]= 4; Break; Case' 5 ': Num[i]= 5; Break; Case' 6 ': Num[i]= 6; Break; Case' 7 ': Num[i]= 7; Break; Case' 8 ': Num[i]= 8; Break; Case' 9 ': Num[i]= 9; Break; default: Throw NewException ("The string to convert is malformed and cannot be converted!") "); } } for(inti = 0; i < num.length; i++) { if(Num[i] < 0 && i > 0) { Throw NewException ("The string to convert is malformed and cannot be converted!") "); } if(Num[i] < 0) { Continue; } retint+ = Math.pow (Ten, Num.length-i-1) *Num[i]; } if(Num[0] = =-1) {//represents a negative numberRetint =-Retint; } returnRetint; } /*** Do not use Java built-in functions to convert string strings to numbers *@paramS *@return * @throwsException*/ Public Static intAtoi2 (String s)throwsexception{intRetint = 0; if(s = =NULL|| S.length () = = 0) { Throw NewException ("The string to be converted is empty and cannot be converted!") "); } BooleanIsnegative =false; for(inti = 0; I < s.length (); i++) { if(i==0) { if(S.charat (i) = = '-') {isnegative=true; Continue; } }Else{ if(S.charat (i) > ' 9 ' | | S.charat (i) < ' 0 '){ Throw NewException ("The string to convert is malformed and cannot be converted!") "); }} retint*=10; Retint+ = S.charat (i)-' 0 '; } returnIsnegative? -Retint:retint; }}
Convert a string string to an int type without using a Java built-in function