简体   繁体   中英

This program keeps on giving me an error: Exception in thread “main” java.lang.StringIndexOutOfBoundsException: String index out of range: 4

When I write a code like this one, I always get this error. It is definitely building the file but is not it just gives me exemption. I am a beginner. Can you guys please help me out and really point out the mistake that I am making.

public static int binToDec(int i)
{
    int[] numbers;//initialize variable
    int f = 4;
    String iString = "" + i;
    int result = 0;
    int length = iString.length();
    numbers = new int[length];
    int power;
    for(power = iString.length(); power>=0;power--)
    {
    while(f == length && f >= 0)
    {

        numbers[power] = iString.charAt(power)^power;
    }

    length--;
    f--;
    }
    for(int g = 0; g <= numbers.length; g++)//double check constraints
    {
        result = numbers[g] = numbers[power];
    }

        return result;
}

The error it is giving me is:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at BaseConvertor.binToDec(BaseConvertor.java:34)
at BaseConvertorTester.main(BaseConvertorTester.java:10)

I also have a tester file. Here it is:

 public class BaseConvertorTester 
  {
public static void main(String args[])

{

    BaseConvertor.binToDec(1010);   

}
}

If a String has length X , it means that it has X characters which are indexed starting from 0 . So the last character will be at index X-1 , not X .

In your for loop you have:

for (power = iString.length(); power >= 0; power--)

but this implies that, if iString has length 4 , it will try to access the character at index 4 , which would be the fifth (non existing in the string, indeed out of range). Try with

for (power = iString.length() - 1; power >= 0; power--)

Change

for(power = iString.length(); power >= 0; power--)

to

for(power = iString.length(); power > 0; power--)

Your loop is starting at 4 then going to 3 then 2 then 1 then 0 which is a total of 5 times when iString.length() is only 4. Changing the >= to > will exclude 0 running it only 4 times.

I'd also change this

String iString = "" + i;

to

String iString = Integer.toString(i);

better programming.

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