不用系统函数将字符串转换成整型

昨天无意中浏览到Magic的博客,发现里面又很多的好东西,讲的是J2EE学习备忘录。里面有很多关于Java基础知识的文章,在算法这个篇章下有一篇是关于不用系统函数将字符串转化为数字,正好前几天的面试我遇到了这个问题,还有些问题没有搞明白,也知道自己的缺点是缺少动手巧代码。结合前几天研究的parseIn()方法的源代码,贴出来让大家看看。里面还有些问题,虽然可以处理各种进制的转换,但是却不能手动输入是多少进制,因为这里有涉及到字符串转数字的操作,希望大家能帮帮忙,看看还有什么更好的办法!

import java.util.*;
public class StringToInt{
public static int StringToInt(String str,int radix){
if(str==null){
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX");
}

if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX");
}
int result=0;//存放结果
boolean negative=false;//标志是否为负数
int start=0;//数字开始位置"+","-"
int len=str.length();//字符串的长度
int limitLeft;//边界值
int digit;//当前字符表示的数字

if(len>0){
if(str.charAt(0)=='-'){//开始字符为负号
negative=true;
limitLeft=Integer.MIN_VALUE;
start++;

}
else if(str.charAt(0)=='+'){//开始字符为正好
negative=false;
limitLeft=-Integer.MAX_VALUE;
start++;

}
else{
limitLeft=-Integer.MAX_VALUE;
}

if(start<len){
digit=Character.digit(str.charAt(start++),radix);
//对于给定的基数,如果是合法的字符(可以转化为数字),
//返回该数字值,否则返回-1.比如digit('3',10)返回3,digit('a',10)返回-1.
if(digit<0){
throw new NumberFormatException("not number");
}else{
result=-digit;
}

}
while(start<len){
digit=Character.digit(str.charAt(start++),radix);
if(digit<0){
throw new NumberFormatException("not number");
}
if(result<(limitLeft/radix)){
throw new NumberFormatException("overflow");
}
result*=radix;
if(result<(limitLeft+digit)){
throw new NumberFormatException("overflow");
}
result-=digit;

}

}
else{
throw new NumberFormatException("exception");
}
if(negative){
if(start>1)
return result;
else
throw new NumberFormatException("not number");
}
else{
return -result;
}

}
public static void main(String args[]){
while (true) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
int radix=16;
try {
System.out.println(StringToInt.StringToInt(str,radix));
}
catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
}




运行结果:
1A
26
-1a
-26
+1d
29
bd
189
gfgh
java.lang.NumberFormatException: not number
at StringToInt.StringToInt(StringToInt.java:41)
at StringToInt.main(StringToInt.java:84)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值