0

Errors out of bounds saying,

java.lang.StringIndexOutOfBoundsException: String index out of range: 6 (in.java.lang.String)

when I run the code. I am trying to find how many identical characters two strings have in the same spots.

Public static void main(String[] args) {
    System.out.println(countAlike("happy","damp");
}

public static int countAlike(String a, String b) {
    int acount = a.length();
    int bcount = b.length();
    int countAlike = 0;
    for(int i = 0; i <= bcount; i++){
        for(int l = 0; l <= bcount; i++){
            if(a.substring(i,i+1).equals(b.substring(l,l+1))){
                countAlike += 1;
            }
            else{ 
            }
        }
    }
    return countAlike;
}
4
  • String index's start at 0, so for(int i = 0; i <= bcount; i++) will go out of bounds on the last iteration. Change it to i < bcount Commented Oct 1, 2018 at 19:34
  • i <= bcount should be i < acount as well as l <= bcount shoul be l < bcount Commented Oct 1, 2018 at 19:36
  • What should this program actually do? Return the amount of equal characters from a and b, keeping position in mind? Commented Oct 1, 2018 at 19:39
  • Yup, forgot to state that! Screw up on my part. Commented Oct 1, 2018 at 20:13

3 Answers 3

1

Indexes for String characters in Java like in most languages start with 0, therefore, the last index of the strings actually is str.length() - 1.

When you test with <=, your variable is incremented until the value is equal to your length, which is an out of bound index.

Rather test with < for both of your tests. Your variable will stop after the last character of that string instead of trying one last time with an index that does not exist.

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

Comments

1

3 issues here:

1) Change <= bcount to < bcount.

2) In your 2nd for loop , you are doing i++ but it should be l++

3) The condition in you first for loop should be i < acount, not i<bcount

Comments

0

When you run this code it will return 3, not sure if that is what you expected for the return value. You have to change a few things

  1. First for loop for(int i = 0; i < acount; i++)
  2. Second for loop for(int l = 0; i < bcount; l++)

    public static void main(String[] args){
    
        System.out.println(countAlike("happy","damp"));
    }
    
    public static int countAlike(String a, String b){
    
        int acount = a.length();
        int bcount = b.length();
        int countAlike = 0;
        for(int i = 0; i < acount; i++){
            for(int l = 0; l < bcount; l++){
                if(a.substring(i,i+1).equals(b.substring(l,l+1))){
                    countAlike += 1;
                    }
                else{}
            }
        }
        return countAlike;
    }
    

If you have a System.out.println(a.substring(i, i+1)); and System.out.println(b.substring(l, l+1)); in your If statement in the for loop if will print out a a p p p p.

Comments