java 字符串转化整型问题
2014-01-10 11:36
330 查看
public class StringParesInteger { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(Integer.MIN_VALUE); System.out.println(Integer.MAX_VALUE/10); System.out.println(pareseInt("=")); } /**本题考查的主要是边界条件 * 1.穿入的字符串是否为空 * 2.字符串的首位是否为(+、-) * 3.字符中是否有非法字符 * 4.穿入的字符串是否超过了整数的最大值(Integer.MAX_VALUE(2147483647)/Integer.MIN_VALUE(-2147483648)) * * @param data * @return */ public static int pareseInt(String data){ /* * 判读穿传入的字符串是否为空 */ if(data==null||data.length()==0){ throw new NullPointerException("data is null"); } int index=0; /** * */ //是否为负数 boolean isPositive=true; // 临界值 int limit = 0; //取出字符串的第一位 char first=data.charAt(0); //第一位是负数的情况下 if(first=='-'){ isPositive=false; index++; //设置整形最小的负数(-2147483648) limit=-Integer.MIN_VALUE; } //第一位是整数的情况下 if(first=='+'){ isPositive=true; //设置最大的正数是(2147483647) limit=Integer.MAX_VALUE; index++; } //设置比较的边界值(214748364) int maxLimit=Integer.MAX_VALUE/10; int length=data.length(); int result=0; while(index<length){ char ch=data.charAt(index); //字符在0-9之间 if(ch>'0'&&ch<'9'){ //先判断原来的值是否大于比较的临界值 if(result>maxLimit){ throw new RuntimeException("整数越界了"); } // 判断当前位的值+ch的值是否》整数的最大值 if(result*10>limit-(ch-'0')){ System.out.println("result-->"+(result*10)); System.out.println("max----->"+(Integer.MAX_VALUE)); System.out.println("result-->"+(Integer.MAX_VALUE-(ch-'0'))+" ch="+(ch-'0')); throw new RuntimeException("数组越界了s "); } index++; result=result*10+(ch-'0'); }else{ throw new RuntimeException("不是整数 "); } } //三目运算符 return isPositive?result:-result; } }
相关文章推荐
- Java字符串分割成字符数组转化为整型
- java 字符串转化为整数溢出问题处理
- JAVA中整型和字符串以及数组和字符串互相转化
- Java中关于Json对象类型和字符串类型之间互相转化的问题
- Java中关于Json对象类型和字符串类型之间互相转化的问题 .
- JAVA如何将ip字符串转化为整型的工具方法
- jsp页面中java脚本整型字符串自动转换问题
- JAVA中字符串转换成整型问题
- java中字符串和整型之间的转化
- java关于split分割字符串,空的字符串不能得到的问题
- 将一串字符串数字转化为整型数字
- 关于java.sql.SQLException: [Microsoft][ODBC 驱动程序管理器] 无效的字符串或缓冲区长度问题
- 关于Java字符串(String)10个最常见问题
- java中枚举类型,整型,字符串之间转换
- Android进步之十四:使用jackon的ObjectMapper的writeValueAsString方法可以把java对象转化成json字符串
- JAVA的整型与字符串相互转换 android
- Java字符串split分割星号*等特殊字符问题
- java 中枚举类型,整型,字符串之间转换
- java把字符串转化为二进制,再把二进制转换成字符串的一个小例子
- 字符串转化为整型1