多读书多实践,勤思考善领悟

如何将String转换为Int

本文于1743天之前发表,文中内容可能已经过时。

有两种方式

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

这两种方式有一点点不同:

  • valueOf返回的是java.lang.Integer的实例
  • parseInt返回的是基本数据类型 int

Short.valueOf/parseShort,Long.valueOf/parseLong等也是有类似差别。

另外还需注意的是,在做int类型转换时,可能会抛出NumberFormatException,因此要做好异常捕获

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.
}

stackoverflow链接:http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java