如何在 Java 中将String转换为int ?
我的字符串只包含数字,我想返回它代表的数字。
例如,给定字符串"1234" ,结果应为数字1234 。
String myString = "1234";
int foo = Integer.parseInt(myString);有关更多信息,请参阅Java 文档 。
例如,有两种方法:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);这些方法之间略有不同:
valueOf返回java.lang.Integer的新实例或缓存实例parseInt返回原始int 。 所有情况都是如此: Short.valueOf / parseShort , Long.valueOf / parseLong等。
好吧,需要考虑的一个非常重要的一点是 Integer 解析器会抛出Javadoc 中所述的 NumberFormatException。
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.
}尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。