码迷,mamicode.com
首页 > 编程语言 > 详细

Java中如何使用非强制类型转换把字符串转换成int类型

时间:2018-01-19 14:12:06      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:代码   char   字符   math   cte   java   trace   int()   pos   

①强制类型转换代码如下:

    String string = "123456";
    int a,b = 0;
    @Test
    public void String2Int1() {
        //方法1
        try {
            a = Integer.parseInt(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //方法2
        try {
            b = Integer.valueOf(string).intValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("a::"+a);
        System.out.println("b::"+b);
    }

②、非强制类型转换

    String string = "123456";
    int a,b = 0;
    @Test
    public void String2Int() {
        for (int i = 0; i < string.length(); i++) {
            try {
                //这里先把每个字符提取出来,例如1*100000,2*10000, 然后相加
                int a = (int) (Character.getNumericValue(string.charAt(i)) * (Math.pow(10, string.length()-i-1)));
                b = a+b;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(b);
    }

 

Java中如何使用非强制类型转换把字符串转换成int类型

标签:代码   char   字符   math   cte   java   trace   int()   pos   

原文地址:https://www.cnblogs.com/liujie-/p/8316059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!