Java自定义实现String转换为int 的简单实现!
public class StringToInt { public static int stringToInt (String str){ char[] num = str.toCharArray();//得到各个字符的char int result = 0; for(int i = 0; i < num.length; i++){ if(num[i]>57||num[i]<48){//0~9对应的Ascall码 System.out.println("数据格式错误,转换失败!!!"); throw new NumberFormatException(); }else{ result+=(num[i]-48)*(Math.pow(10, num.length-i-1)); } } return result; } public static void main(String[] args) { String str = "612345"; //String str="612346a";//错误格式测试 int sum=stringToInt(str); System.out.println(sum); } }
时间: 2024-10-09 04:44:48