public class DuplicateLetters {
// CW2.2 Lab-Group-06 Question 5
// You are given two non-empty strings source and target, all lowercase letters, from a user.
// The user intends to type the string given in target.
// However, due to using an old keyboard,
// when the user was typing, a number characters may be duplicated, and typed one or more times.
// The source is what the user actually typed, which may or may not be the intended target.
// Return true if and only if it is possible that some characters of target have been duplicated in source,
// while the user intended to type the target string.
// You must use String methods in lecture notes.
// You must NOT use StringBuilder or Regular Expression methods.
public static boolean duplicateLetters(String source, String target) {
boolean test = false;
for(int i=0; i<source.length(); i++) {
for(int j=i; j<target.length(); j++) {
if(Character.toString(source.charAt(i)).equals(Character.toString(target.charAt(j)))) {
test = true;
}
else {
test = false;
j--;
}
i++;
}
}
return test;
}
public static void main(String[] args) {
System.out.println(duplicateLetters("andddrew", "andrew"));
// true, there are duplicated letters typed
System.out.println(duplicateLetters("lllejiiee", "leejie"));
// false, note the initial letter e
// there is only one initial e in the source, whereas there is a double initial ee in the target
System.out.println(duplicateLetters("cherry", "cherry"));
// true, no duplicated letters typed this time
}
This is my code for that question, but it keeps getting the java.lang.StringIndexOutOfBounds error. So, I want to know what is wrong with my code, and how to improve this.