如何在 Java 中将 String 转换为 int? [英] How do I convert a String to an int in Java?
问题描述
如何在 Java 中将 String
转换为 int
?
How can I convert a String
to an int
in Java?
我的字符串只包含数字,我想返回它代表的数字.
My String contains only numbers, and I want to return the number it represents.
例如,给定字符串"1234"
,结果应该是数字1234
.
For example, given the string "1234"
the result should be the number 1234
.
推荐答案
String myString = "1234";
int foo = Integer.parseInt(myString);
如果您查看 Java 文档 你会注意到catch"就是这个函数会抛出NumberFormatException
,当然你要处理:
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:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
foo = 0;
}
(这种处理默认格式错误的数字为 0
,但如果您愿意,您可以做其他事情.)
(This treatment defaults a malformed number to 0
, but you can do something else if you like.)
或者,您可以使用 Guava 库中的 Ints
方法,该方法与 Java 8 的 Optional
相结合,提供了一种强大而简洁的方法将字符串转换为一个整数:
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:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
这篇关于如何在 Java 中将 String 转换为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!