2013-01-05 22 views

回答

6

使用Integer.valueOf

int i = Integer.valueOf(someString); 

(还有其他的选择也是如此。)

+0

是的,那会的。 谢谢 –

+2

这将工作,但有不必要的拳击和拆箱。最好使用'Integer.parseInt(...)'作为原始的'int'。 – msandiford

+0

是的。根据文档,valueOf返回一个** Integer Object **,而parseInt返回一个**原始的int **,这就是你想要的。 (http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29) – wullxz

3

看静态方法Integer.parseInt(String string)。此方法过载,并且还能够读取除十进制系统之外的其他数字系统中的值。如果string不能被解析为整数,该方法将引发它可以钓到作为NumberFormatException如下:

string = "1234" 
try { 
    int i = Integer.parseInt(string); 
} catch (NumberFormatException e) { 
    System.err.println(string + " is not a number!"); 
} 
2

除了什么戴夫wullxz说,你也可以用户正则表达式查找如果测试过的字符串符合你的格式,例如

import java.util.regex.Pattern; 
... 

String value = "23423423"; 

if(Pattern.matches("^\\d+$", value)) { 
    return Integer.valueOf(value); 
} 

使用正则表达式,你也可以恢复其他类型的数字,如双打,例如,

String value = "23423423.33"; 
if(Pattern.matches("^\\d+$", value)) { 
    System.out.println(Integer.valueOf(value)); 
} 
else if(Pattern.matches("^\\d+\\.\\d+$", value)) { 
    System.out.println(Double.valueOf(value)); 
} 

我希望这将有助于解决您的问题。

编辑

此外,由wullxz建议,你可以使用Integer.parseInt(String)代替Integer.valueOf(String)parseInt返回intvalueOf返回Integer实例。从性能角度来看,推荐使用parseInt

+1

我建议你改变你的使用'valueOf'分别为'parseInt'和'parseDouble'。 (请参阅** Dave **的回答下的评论) – wullxz

+0

@wullxz非常好;从性能角度来看,推荐使用该方法(+1)。 – Tom

相关问题