如何将String转换为Int

有两种方式java

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

这两种方式有一点点不一样:this

  • valueOf返回的是java.lang.Integer的实例spa

  • parseInt返回的是基本数据类型 intcode

Short.valueOf/parseShort,Long.valueOf/parseLong等也是有相似差异。orm

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

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.
    }