溫馨提示×

java中string轉(zhuǎn)int怎么實(shí)現(xiàn)

小億
92
2023-12-20 01:44:08
欄目: 編程語言

在Java中,可以使用Integer類的parseInt()方法將字符串轉(zhuǎn)換為整數(shù)。這個方法的使用方法如下:

String str = "123"; // 要轉(zhuǎn)換的字符串
int num = Integer.parseInt(str); // 將字符串轉(zhuǎn)換為整數(shù)

另外,如果要處理可能包含非數(shù)字字符的字符串,可以使用try-catch塊來捕獲NumberFormatException異常,以處理轉(zhuǎn)換失敗的情況。

String str = "123a"; // 要轉(zhuǎn)換的字符串
try {
    int num = Integer.parseInt(str); // 將字符串轉(zhuǎn)換為整數(shù)
    System.out.println(num);
} catch (NumberFormatException e) {
    System.out.println("字符串無法轉(zhuǎn)換為整數(shù)");
}

0