如何在Java中將String
轉換為int
?
我的String只包含數字,我想返回它表示的數字.
例如,給定字串"1234"
的結果應該是數字1234
.
String myString = "1234";
int foo = Integer.parseInt(myString);
如果您檢視 Java Documentation ,您會注意到“catch”是這個函式可以丟擲NumberFormatException
,當然您必須處理:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
foo = 0;
}
(這種治療預設為0
,但如果你喜歡,你可以做其他事情.)
或者,您可以使用來自Guava庫的Ints
方法,該方法與Java 8的Optional
結合使用強大簡潔的方法將字串轉換為int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)