如何将String转换为int?

"1234"  →  1234

当前回答

使用Integer.parseInt()并将其放入try。。。catch块来处理任何错误,例如,

private void ConvertToInt(){
    String string = txtString.getText();
    try{
        int integerValue=Integer.parseInt(string);
        System.out.println(integerValue);
    }
    catch(Exception e){
       JOptionPane.showMessageDialog(
         "Error converting string to integer\n" + e.toString,
         "Error",
         JOptionPane.ERROR_MESSAGE);
    }
 }

其他回答

方法:

整数.parseInt整数.parseInt(s,基数)Integer.parseInt(s,beginIndex,endIndex,基数)整数.parseUnsignedInt整数.parseUnsignedInt(s,基数)Integer.parseUnsignedInt(s,beginIndex,endIndex,基数)整数.valueOf整数.valueOf(s,基数)整数.解码数字Utils.toInt(s)NumberUtils.toInt(s,默认值)


Integer.valueOf生成一个Integer对象,而所有其他方法生成一个基元int。

最后两个方法来自commons-lang3和一篇关于转换的大文章。

嗯,需要考虑的一个非常重要的点是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.
}

在尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。

我们可以使用Integer包装器类的parseInt(Stringstr)方法将String值转换为整数值。

例如:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

Integer类还提供了valueOf(Stringstr)方法:

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

我们还可以使用NumberUtils实用程序类的toInt(StringstrValue)进行转换:

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);

公共静态int parseInt(字符串)引发NumberFormatException

可以使用Integer.parseInt()将字符串转换为int。

将字符串“20”转换为原始int:

String n = "20";
int r = Integer.parseInt(n); // Returns a primitive int
System.out.println(r);

输出-20

如果字符串不包含可解析的整数,则将引发NumberFormatException:

String n = "20I"; // Throws NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

公共静态Integer valueOf(字符串)引发NumberFormatException

您可以使用Integer.valueOf()。在这种情况下,它将返回一个Integer对象。

String n = "20";
Integer r = Integer.valueOf(n); // Returns a new Integer() object.
System.out.println(r);

输出-20

工具书类https://docs.oracle.com/en/

有多种方法可以将字符串int值转换为Integer数据类型值。您需要处理字符串值问题的NumberFormatException。

整数.分析Intfoo=整数.parseInt(myString);整数值foo=Integer.valueOf(myString);使用Java 8可选APIfoo=可选.Nullable(myString).map(整数::parseInt).get();