String myString = "1234";
int foo = Integer.parseInt(myString);
If you look at the Java Documentation you'll notice the "catch" is that this function can throw a NumberFormatException
, which of course you have to handle:
(如果您查看Java文档,您会发现“捕获”是此函数可以引发NumberFormatException
,当然您必须处理:)
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
foo = 0;
}
(This treatment defaults a malformed number to 0
, but you can do something else if you like.)
((此处理方式默认将格式错误的数字设置为0
,但您可以根据需要执行其他操作。))
Alternatively, you can use an Ints
method from the Guava library, which in combination with Java 8's Optional
, makes for a powerful and concise way to convert a string into an int:
(另外,您可以使用Guava库中的Ints
方法,该方法与Java 8的Optional
结合使用,提供了一种强大而简洁的方法来将字符串转换为int:)
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…