I'm not sure if I entirely understand what you're trying to achive, but the whole logic of your method is flawed.
One problem is, obviously, that your function will return true
if just the last character matches, since substring(word.length() - 1)
will check whether the last character is contained in the other string. In every other loop, you are checking whether an entire sequence is contained, starting with the entire string and reducing the amount of characters every loop.
Even if you add characters to word
that are not in randomString
, the function will return true as long as they are not at the end of the string.
Something like this should be what you were looking for originally:
public static boolean checkWord() {
String randomString = "BFEABLDEG";
String word = "LABEL";
for (int i = 0; i < word.length(); i++) {
if (randomString.indexOf(word.charAt(i)) == -1) {
return false;
}
}
return true;
}
A simple solution to also check for duplicated characters is to remove one occurrence of the character in the string. There are certainly more efficient solutions possible, make sure to check the thread linked in the comments.
public static void main(String[] args) throws Exception {
System.out.println(test("BFEABLDEG", "LABEL"));
}
public static boolean test(String searchIn, String searchFor) {
for (char c : searchFor.toCharArray()) {
if (searchIn.indexOf(c) == -1) {
return false;
}
searchIn = searchIn.replaceFirst(Character.toString(c), "");
}
return true;
}