①强制类型转换代码如下:
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); }
原文地址:https://www.cnblogs.com/liujie-/p/8316059.html
时间: 2024-10-10 15:13:52