String string = "123"; Integer value = Integer.valueOf(string); System.out.println("stringToInt1---------->"+value);
结果:StringToInt1---------->123
以上两种方法都是可行的。
但是会有特殊的情况,比如:
1 2 3 4 5 6 7 8 9 10 11
String string = "abc"; int value = Integer.parseInt(string); System.out.println("stringToInt---------->"+value);
结果: Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at com.hand.todo.infra.util.StringToInt.stringToInt(StringToInt.java:16) at com.hand.todo.infra.util.StringToInt.main(StringToInt.java:10)
String string = "abc"; int value = 0; try { value = Integer.parseInt(string); } catch (NumberFormatException e) { e.printStackTrace(); } System.out.println("StringToInt---------->"+value);
结果: java.lang.NumberFormatException: For input string: "abc" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at com.hand.todo.infra.util.StringToInt.stringToInt(StringToInt.java:18) at com.hand.todo.infra.util.StringToInt.main(StringToInt.java:10) StringToInt---------->0