zoukankan      html  css  js  c++  java
  • Java中如何使用非强制类型转换把字符串转换成int类型

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

        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);
        }
  • 相关阅读:
    Uboot USB模式(RK3288变砖头的解决办法)
    C++ 解析一
    C++基础
    shell脚本分析二
    ASCII
    POJ 1970 The Game (DFS)
    PoJ1979 Red and Black (DFS)
    UVA 572 Oil Deposits (DFS)
    打印日历
    求第N个素数
  • 原文地址:https://www.cnblogs.com/liujie-/p/8316059.html
Copyright © 2011-2022 走看看