Question

I have an error in my program on execution.

The error was:

 --------------------Configuration: <Default>--------------------
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
    at java.lang.String.charAt(String.java:687)
    at codeinstaneous.main(codeinstaneous.java:19)

Process completed. Why might this be occurring? This is my code:

import javax.swing.*;

public class codeinstaneous {
    public static void main (String[] args) {
        String theCode;
        theCode = JOptionPane.showInputDialog("Enter the code to decoded it :");
        char theBit;
        char theSource='a';
        int i=0;
        for(i=0;i <= theCode.length() ;i++){
            theBit = theCode.charAt(i);
            if(theBit=='0')
                i++;
        if(theBit=='0')
            theSource='1';
        }    
        JOptionPane.showMessageDialog(null,theSource);
    }    
}
Was it helpful?

Solution

This line:

for(i=0; i <= theCode.length();i++){

Should have a < and not <=. This is because you are executing the for loop for the length of that string and one more. Since a String is a zero based array, you try to find the character when i = the length, and you can't, because there is no character there. It throws an exception because of this, since it can't find that character. So to fix this, use this code:

for(i=0; i < theCode.length();i++){

OTHER TIPS

Change

for(i=0; i <= theCode.length(); i++)

to

for(i=0; i < theCode.length(); i++)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top