问题

如何在Java中将String转换为int

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

例如,给定字符串“1234”,结果应该是数字“1234”。


#1 热门回答(3506 赞)

String myString = "1234";
int foo = Integer.parseInt(myString);

有关更多信息,请参阅Java Documentation


#2 热门回答(581 赞)

例如,这里有两种方法:

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

这些方法之间略有不同:

  • valueOf返回一个新的或缓存的java.lang.Integer实例
  • parseInt返回基元int。

对于所有情况也是如此:Short.valueOf /parseShortLong.valueOf /parseLong


#3 热门回答(212 赞)

那么,需要考虑的一个非常重要的问题是整数解析器抛出NumberFormatException,如3144835117中所述。

int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
      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.
}

尝试从split参数获取整数值或动态解析某些内容时处理此异常很重要。


原文链接