Reputation: 11
public class Launcher {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
final String CAMBRIDGE = "CAMBRIDGE";
System.out.println("Enter word.");
String word = sc.nextLine();
StringBuilder wordSB = new StringBuilder(word);
StringBuilder camSB = new StringBuilder(CAMBRIDGE);
System.out.println(wordSB.length());
System.out.println(camSB.length());
for (int i = 0; i < wordSB.length(); i++) {
for (int j = 0; j < camSB.length(); j++) {
if (wordSB.charAt(i) == camSB.charAt(j)) {
System.out.println(wordSB.charAt(i));
System.out.println(camSB.charAt(j));
wordSB.deleteCharAt(i);
} // end if
} // end second for
} // end for
System.out.println(wordSB.toString());
sc.close();
}
}
I was trying to compare duplicated element, but I got "java.lang.StringIndexOutOfBoundsException: index 3, length 3" error message from this line when I enter LOVA as an input for checking duplicated letter A.
if (wordSB.charAt(i) == camSB.charAt(j))
I assume the issue is from the nested for loop, but I couldn't figure out how to solve that. Thanks in advance.
Upvotes: 0
Views: 39
Reputation: 18002
The line wordSB.deleteCharAt(i);
removes a character from wordSB
, which means that the index i
may point to something that is no longer there. This can be problematic once your inner for-loop iterates to the next value of j
. I'm not sure what you're trying to do but you may want to break from your inner-loop after you've deleted the character by adding a break;
after the wordSB.deleteCharAt(i);
line.
Upvotes: 1
Reputation: 148
You are deleting characters from a string while using its length to iterate over it. Removing/Deleting a char will shorten the string -> the character at index i w won't be the one you expected, resulting in a out of bounds exception at the end, because you keep skipping characters.
Try it out with a simple println of the string while removing the chars with the same for-loop and you will understand the problem.
Upvotes: 1