如何将String转换为int?

"1234"  →  1234

当前回答

例如,这里有两种方法:

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

这些方法略有不同:

valueOf返回java.lang.Integer的新实例或缓存实例parseInt返回基元int。

所有情况都是一样的:Short.valueOf/parseShort、Long.valueOf/parseLong等。

其他回答

我们可以使用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);

嗯,需要考虑的一个非常重要的点是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(yourString)。

记住以下几点:

整数.parseInt(“1”);//好啊

整数.parseInt(“-1”);//好啊

整数.parseInt(“+1”);//好啊

整数.parseInt(“1”);//异常(空格)

整数.parseInt(“2147483648”);//异常(整数限制为最大值2147483647)

整数.parseInt(“1.1”);//异常(.或,或任何不允许的)

Integer.parseInt(“”);//异常(不是0或其他)

只有一种类型的异常:NumberFormatException

使用Java integer类的parseInt方法将字符串转换为整数。parseInt方法将字符串转换为int,如果字符串无法转换为int类型,则抛出NumberFormatException。

忽略它可能引发的异常,请使用以下命令:

int i = Integer.parseInt(myString);

如果变量myString表示的字符串是有效的整数,如“1234”、“200”、“1”,它将被转换为Java int。如果由于任何原因失败,则更改可能引发NumberFormatException,因此代码应该稍长一些才能解释这一点。

例如,Java String到int的转换方法,控制可能的NumberFormatException

public class JavaStringToIntExample
{
  public static void main (String[] args)
  {
    // String s = "test";  // Use this if you want to test the exception below
    String s = "1234";

    try
    {
      // The String to int conversion happens here
      int i = Integer.parseInt(s.trim());

      // Print out the value after the conversion
      System.out.println("int i = " + i);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

如果更改尝试失败(在本例中,如果您可以尝试将Java String测试转换为int),Integer parseInt进程将抛出NumberFormatException,您必须在try/catch块中处理该异常。

将String转换为Int的一些方法如下:

可以使用Integer.parseInt():字符串测试=“4568”;int new=Integer.parseInt(测试);也可以使用Integer.valueOf():字符串测试=“4568”;int new=Integer.valueOf(测试);