【问题】
需要将一个字符串,可能是十进制:
比如
123
也可能是16进制:
0x123
转换为int值。
【折腾过程】
1.参考:
How to convert string to int in Java?
去试试,
1 2 3 4 5 6 7 8 | void strToIntTest(){ String testStr1 = "123" ; String testStr2 = "0x123" ; int convertedIntValue1 = Integer.parseInt(testStr1); int convertedIntValue2 = Integer.parseInt(testStr2); System.out.println( "convertedIntValue1=" + convertedIntValue1 + ", convertedIntValue2=" + convertedIntValue2); } |
应该就可以了。
结果调试发现:
1 | int convertedIntValue2 = Integer.parseInt(testStr2); |
会挂掉。
2.然后自己去试试,通过自带文档,发现有个decode:
然后去试试:
1 2 3 4 5 6 7 8 9 10 | void strToIntTest(){ String testStr1 = "123" ; String testStr2 = "0x456" ; int convertedIntValue1 = Integer.parseInt(testStr1); //int convertedIntValue2 = Integer.parseInt(testStr2); int convertedIntValue2 = Integer.decode(testStr2); System.out.println( "convertedIntValue1=" + convertedIntValue1 + ", convertedIntValue2=" + convertedIntValue2); } |
结果,虽然工作了。
却又遇到:
【已解决】android中使用System.out.println结果不工作:无法在ADT的LogCat或console中看到输出结果
【总结】
直接调用
Integer.parseInt
即可将string转为int,但是不支持0x123的形式。
最后去用:
Integer.decode("0x123");
才可以。
转载请注明:在路上 » 【已解决】android中的java中的string转int