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

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

我怎么能转换StringintJava中?

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

例如,给定字符串"1234",结果应该是数字1234


陪伴而非守候
浏览 765回答 4
4回答

汪汪一只猫

String myString = "1234";int foo = Integer.parseInt(myString);如果你查看Java文档,你会注意到“catch”是这个函数可以抛出一个NumberFormatException,当然你必须处理:int foo;try {    foo = Integer.parseInt(myString);}catch (NumberFormatException e){    foo = 0;}(此处理默认为格式错误的数字0,但如果您愿意,可以执行其他操作。)或者,您可以使用IntsGuava库中的方法,该方法与Java 8结合使用Optional,可以将字符串转换为int的强大而简洁的方法:import com.google.common.primitives.Ints;int foo = Optional.ofNullable(myString)  .map(Ints::tryParse)  .orElse(0)

UYOU

例如,有两种方法:Integer x = Integer.valueOf(str);// orint y = Integer.parseInt(str);这些方法之间略有不同:valueOf 返回一个新的或缓存的实例 java.lang.IntegerparseInt返回原语int。所有情况都是如此:Short.valueOf/ parseShort,Long.valueOf/ parseLong等。

斯蒂芬大帝

好吧,需要考虑的一个非常重要的一点是,Integer解析器会抛出Javadoc中所述的NumberFormatException 。int foo;String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exceptionString StringThatCouldBeANumberOrNot2 = "26263";  //will not throw exceptiontry {       foo = Integer.parseInt(StringThatCouldBeANumberOrNot);} catch (NumberFormatException e) {       //Will Throw exception!       //do something! anything to handle the exception.}try {       foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);} catch (NumberFormatException e) {       //No problem this time, but still it is good practice to care about exceptions.       //Never trust user input :)       //Do something! Anything to handle the exception.}尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。
打开App,查看更多内容
随时随地看视频慕课网APP