【Java】字符串转换为数字:Integer的parseInt方法
Java官方文檔[1]的解釋
public static int parseInt?(String s) throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be
decimal digits, except that the first character may be an ASCII minus sign ‘-’ (’\u002D’) to indicate
a negative value or an ASCII plus sign ‘+’ (’\u002B’) to indicate a positive value. The resulting
integer value is returned, exactly as if the argument and the radix 10 were given as arguments to
the parseInt(java.lang.String, int) method.
_
Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.
中文翻譯
我來(lái)簡(jiǎn)單翻譯一部分。
對(duì)于Integer類(lèi)的靜態(tài)方法public static int parseInt?(String s) throws NumberFormatException
它能夠?qū)tring類(lèi)型的參數(shù),解析為一個(gè)帶符號(hào)的十進(jìn)制整數(shù)。字符串中的字符,必須是十進(jìn)制數(shù)字,在這個(gè)十進(jìn)制數(shù)字的第一個(gè)字符前,可以是ASCII字符的-或Unicode字符的'\u002D來(lái)表明這是一個(gè)負(fù)值,或者是一個(gè)ASCII字符的+或Unicode字符的'\u002B來(lái)表明這是一個(gè)正值。這個(gè)作為結(jié)果的整數(shù)值會(huì)被return,如果使用方法parseInt(java.lang.String, int)并為其傳參(String s,10)也能達(dá)到和當(dāng)前方法一樣的效果。
- 參數(shù):
- s: 一個(gè)要被解析的字符串,這個(gè)字符串看起來(lái)是一個(gè)整數(shù)
- 返回值:
- 一個(gè)整數(shù)值,它由十進(jìn)制數(shù)字表示
- 異常拋出:
- NumberFormatException:如果字符串沒(méi)有包含可以被解析的整數(shù)
極簡(jiǎn)解釋 & 應(yīng)用
簡(jiǎn)而言之,我們就是要將String類(lèi)型的整數(shù)轉(zhuǎn)化成int類(lèi)型的整數(shù)。
字符串只允許出現(xiàn)十進(jìn)制數(shù)字、正號(hào)(+)和負(fù)號(hào)(-),當(dāng)然,如果是Unicode編碼也可以,一般不會(huì)這樣用。
我們先來(lái)列舉一些正確的例子,如:
示例代碼:
String s = "100"; int sToInt = Integer.parseInt(s);但是,如果字符串出現(xiàn)了其他符號(hào),就會(huì)拋出NumberFormatException。
例如:
我們需要捕獲并且處理這個(gè)異常,給出一個(gè)示例代碼。
public class TestSubmitException {public static void main(String[] args) {String[] salesOrders = {"1111", "28120821", "-111", "+1111", "1.11", "abc"};submitOrders(salesOrders);}public static void submitOrders(String[] salesOrders) {int[] salesOrdersInteger = new int[salesOrders.length];try {int i = 0;for (String s : salesOrders) {salesOrdersInteger[i] = Integer.parseInt(s);i++;}} catch (NumberFormatException e) { e.printStackTrace();}for (int a : salesOrdersInteger) {System.out.println(a);}} }運(yùn)行結(jié)果是
我們可以看到最后Process finished with exit code 0,說(shuō)明程序,成功處理了異常并且正常退出了。
參考資料
[1] Java11官方文檔 Integer.parseInt(String s)
總結(jié)
以上是生活随笔為你收集整理的【Java】字符串转换为数字:Integer的parseInt方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 输卵管都切除了能试管怀孕吗
- 下一篇: 【Java】异常处理的目的