| Home >> All >> diagapplet >> [ CodeGen Javadoc ] |
Source code: diagapplet/CodeGen/StrToInt.java
1 package diagapplet.CodeGen; 2 3 import java.util.*; 4 5 /* 6 * 7 * StrToInt 8 * 9 */ 10 public class StrToInt 11 { 12 public static int convert(String str) throws NumberFormatException 13 { 14 int multiplier = 1; 15 StringTokenizer tokenizer = new StringTokenizer(str," \t\r\n\b:;[]()+"); 16 while(tokenizer.hasMoreTokens()) 17 { 18 multiplier = 1; 19 String token = tokenizer.nextToken(); 20 if(null == token) 21 { 22 throw new NumberFormatException(str); 23 } 24 if(token.startsWith("-")) 25 { 26 multiplier = -1; 27 token = token.substring(1); 28 } 29 int point_index = token.indexOf("."); 30 if(point_index > 0) 31 { 32 token = token.substring(0,point_index); 33 } else if(point_index == 0) 34 { 35 return 0; 36 } 37 try 38 { 39 if(token.startsWith("0x")) 40 { 41 return multiplier * Integer.parseInt(token.substring(2), 16); 42 } 43 else if(token.startsWith("0") && !token.equals("0")) 44 { 45 return multiplier * Integer.parseInt(token.substring(1), 8); 46 } 47 else 48 { 49 return multiplier * Integer.parseInt(token); 50 } 51 } 52 catch(NumberFormatException e) 53 { 54 continue; 55 } 56 } 57 throw new NumberFormatException(str); 58 } 59 60 61 public static void main(String args[]) 62 { 63 System.out.println("convert(3.14) = "+convert("3.14")); 64 System.out.println("convert(((NMLTYPE) 1006)) = "+convert("((NMLTYPE) 1006)")); 65 66 System.out.println("convert((32)) = "+convert("(32)")); 67 System.out.println("convert((0x100)) = "+convert("(0x100)")); 68 } 69 }