Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

java - 如何在Java中将String转换为int?(How do I convert a String to an int in Java?)

How can I convert a String to an int in Java?

(如何在Java中将String转换为int ?)

My String contains only numbers, and I want to return the number it represents.

(我的字符串仅包含数字,我想返回它代表的数字。)

For example, given the string "1234" the result should be the number 1234 .

(例如,给定字符串"1234" ,结果应为数字1234 。)

  ask by Unknown user translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...