题目:把一个字符串转换成整数。
考虑的问题:
1、空指针;
2、包含非数字字符;
3、包含正负号;
4、最大正整数;
5、最小负整数;
6、溢出(还没考虑)
代码:
1 package com.yyq; 2 import java.util.regex.Matcher; 3 import java.util.regex.Pattern; 4 5 /** 6 * Created by Administrator on 2015/9/4. 7 */ 8 public class StringToInt { 9 public static void main(String args[]) { 10 String str = "-123"; 11 int integer = strToInt(str); 12 System.out.println("number: "+integer); 13 } 14 15 public static int strToInt(String str) { 16 int number = 0; 17 int flag = 0; 18 int subflg = 0; 19 str.trim(); 20 try { 21 if (str == null || str == "") { 22 System.out.println("String is null."); 23 return 0; 24 } 25 char c[] = str.toCharArray(); 26 String newStr = null; 27 if(c[0] == ‘-‘ || c[0] == ‘+‘){ 28 flag = 1; 29 if(c[0] == ‘-‘) subflg = 1; 30 newStr = new String(c,1,c.length-1); 31 System.out.println(newStr); 32 } 33 34 Pattern pattern = Pattern.compile("[a-zA-Z]+"); 35 Matcher mat = pattern.matcher(newStr); 36 if (mat.matches()) { 37 System.out.println("String contains character."); 38 number = 0; 39 } else { 40 if(flag == 1) { 41 for (int i = 1; i < c.length; i++) 42 number = number * 10 + c[i] - ‘0‘; 43 if (subflg == 1) 44 number = number * -1; 45 } 46 System.out.println("Integer: "+Integer.parseInt(str)); 47 } 48 }catch (Exception e){ 49 e.printStackTrace(); 50 } 51 return number; 52 } 53 }
时间: 2024-10-17 18:02:56