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);
    }    
}
有帮助吗?

解决方案

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++){

其他提示

Change

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

to

for(i=0; i < theCode.length(); i++)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top