简体   繁体   中英

NumberFormatException when using substring()

I'm attempting to determine whether or not a string is made up of sequential integers using the code below. However, it throws a NumberFormatException when I run it.

I have determined this is caused by using the variable i as the index values for substring().

This has really frustrated me as I cannot find another way to do it. Does anyone know why substring() cannot use variables as index values and what I could do to fix/ circumvent this issue? (other than using a giant if statement ) Any help would be really appreciated! Thanks!

public  static void main(String[] args) {

    String x = "12345";
    int counter = 0;

    for (int i = 0; i < 5; i++) {
        if (Integer.parseInt(x.substring(0, 1)) == (Integer.parseInt(x.substring(i, i++))) - i) {
            counter++;
        }  
    }

    if (counter == 5) {
        System.out.println("String is sequential");
    }
}

x.substring(i, i++) is the same as x.substring(i, i) (as far as the values passed to substring are concerned) which gives an empty String. Calling Integer.parseInt on an empty String gives NumberFormatException .

To fix your current loop :

for (int i = 1; i < x.length(); i++) { // note the range change
    // using (i,i+1) instead of gives you a single character
    if (Integer.parseInt(x.substring(0, 1)) == (Integer.parseInt(x.substring(i, i+1)))-i) {
        counter++;
    }  
}

Or, you can avoid using substring at all. Simply iterate over the characters of the String :

for (int i = 1; i < x.length(); i++) {
    if (x.charAt(0) == x.charAt(i) - i) {
        counter++;
    }  
}

Change your code like this:

if (Integer.parseInt(x.substring(0, 1)) == (Integer.parseInt(x.substring(i, i+1))) - i) {

And it should work.

There's no need to extract a substring and then parse it back to an integer.

Character.getNumericValue(x.charAt(0)) == Character.getNumericValue(x.charAt(i))

would do the same, provided all of the characters are digits. In the case that the characters aren't digits, it wouldn't throw the NumberFormatException .

     (Integer.parseInt(x.substring(i, i++))) 

这将返回空字符串,您需要使其成为++ i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM