string转换为bigdecimal_java如何将String转换为Int
問題:
java如何將String轉換為Int
? ? ? ?答案:
有兩種方式
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
這兩種方式有一點點不同:
valueOf返回的是?java.lang.Integer的實例
parseInt返回的是基本數據類型 int
Short.valueOf/parseShort, Long.valueOf/parseLong等也是有類似差別。
另外還需注意的是,在做int類型轉換時,可能會拋出NumberFormatException,因此要做好異常捕獲
int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
}
try {
foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
//No problem this time but still it is good practice to care about exceptions.
//Never trust user input :)
//do something! anything to handle the exception.
}
這將會是一個系列,我接下來會更新mysql,mongodb,java,linux等,精挑 Stack Overflow在中排名前的問題,一般知道這些問題,可以幫助我們快速解決開發中遇到80%的問題。
推薦閱讀:
用一年的時間帶你讀懂《深入理解計算機系統》
500+ 免費的中文編程電子書
總結
以上是生活随笔為你收集整理的string转换为bigdecimal_java如何将String转换为Int的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: catia目录编辑器使用教程_如何去编辑
- 下一篇: javascript取随机数_查缺补漏一