Java 必知必会 第 1 篇
(精挑 Stack Overflow在java中排名前100的问题
懂得这些问题的答案帮你解决80%开发问题 )
问题:
java如何将String转换为Int
       答案:
有两种方式
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,因此要做好异常捕获
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.
}
这将会是一个系列,我接下来会更新mysql,mongodb,java,linux等,精挑 Stack Overflow在中排名前的问题,一般知道这些问题,可以帮助我们快速解决开发中遇到80%的问题。
推荐阅读:

 京公网安备 11010502036488号
京公网安备 11010502036488号