How do I convert a String to an int in Java?

2018-12-30 23:29发布

How can I convert a String to an int in Java?

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

30条回答
梦寄多情
2楼-- · 2018-12-30 23:58

Here we go

String str="1234";
int number = Integer.parseInt(str);
print number;//1234
查看更多
余欢
3楼-- · 2018-12-30 23:59

Do it manually:

public static int strToInt( String str ){
    int i = 0;
    int num = 0;
    boolean isNeg = false;

    //Check for negative sign; if it's there, set the isNeg flag
    if (str.charAt(0) == '-') {
        isNeg = true;
        i = 1;
    }

    //Process each character of the string;
    while( i < str.length()) {
        num *= 10;
        num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
    }

    if (isNeg)
        num = -num;
    return num;
}
查看更多
零度萤火
4楼-- · 2018-12-30 23:59
int foo=Integer.parseInt("1234");

Make sure there is no non-numeric data in the string.

查看更多
泛滥B
5楼-- · 2018-12-31 00:01

Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.

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

It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

查看更多
几人难应
6楼-- · 2018-12-31 00:02

For normal string you can use:

int number = Integer.parseInt("1234");

For String builder and String buffer you can use:

Integer.parseInt(myBuilderOrBuffer.toString());
查看更多
后来的你喜欢了谁
7楼-- · 2018-12-31 00:03

An alternate solution is to use Apache Commons' NumberUtils:

int num = NumberUtils.toInt("1234");

The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.

Apache NumberUtils API Version 3.4

查看更多
登录 后发表回答