为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

陪伴而非守候 2019-05-24 15:51:33
如何在Java中将String转换为int?我怎么能转换String成intJava中?我的字符串只包含数字,我想返回它代表的数字。例如,给定字符串"1234",结果应该是数字1234。
查看完整描述

4 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

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)


查看完整回答
反对 回复 2019-05-24
?
UYOU

TA贡献1878条经验 获得超4个赞

例如,有两种方法:

Integer x = Integer.valueOf(str);// orint y = Integer.parseInt(str);

这些方法之间略有不同:

  • valueOf 返回一个新的或缓存的实例 java.lang.Integer

  • parseInt返回原语int

所有情况都是如此:Short.valueOfparseShortLong.valueOfparseLong等。


查看完整回答
反对 回复 2019-05-24
?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

好吧,需要考虑的一个非常重要的一点是,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.}

尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。


查看完整回答
反对 回复 2019-05-24
  • 4 回答
  • 0 关注
  • 762 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信