0

I get the following error in my java code:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6

...which occurs at the following line:

if (strFactor.charAt(j) == strProduct.charAt(k)) {

Here is the code:

       for (int j=0; 0<=5; j++) {
            same = false;
            for (int k=0; k<=5; k++) {
                if (strFactor.length() == 6 && strProduct.length() == 6) {
                    if (strFactor.charAt(j) == strProduct.charAt(k)) {
                        same = true;
                    }
                }
            }
            if (!same) {
                return false;
            }
        }

Anyone have any idea why the index would ever be out of range?

4 Answers 4

1

I'm no Java programmer, but 0<=5 will always evaluate to true, so j reaches 6 (and would keep going were it not for that exception).

Sign up to request clarification or add additional context in comments.

2 Comments

you have no idea how long i've fretted over this. thanks for pointing out my stupidity! :)
There have got to be better ways of solving this problem, but that wasn't the question being asked ;-)
1

for (int j=0; 0<=5; j++) { should be for (int j=0; j<=5; j++) {

Comments

1

Look at the first line of your forloop. The string is going out of bounds

for (int j=0; 0<=5; j++) {

Correct the condition. Always be careful when you code !! Happy Coding

Comments

0

Hey man: Your j_for is wrong...It should be for(int j=0; j<=5; j++),but you write 0<=5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.