I am creating a program that takes in two strings and then compares the two to determine if the characters of the first string are contained in the second string (in no order).
I used a count integer to keep track of position
Unfortunately, I am getting StringIndexOutOfBoundsException: String index out of range: 0
upon executing the main and entering in "elf" for the first word, and "self" for the second for example.
public static boolean containedWordsCheck(String firstWord, String secondWord, int count) {
//Default rule for setting to false if the size of the first word is larger than the second
if (firstWord.length() > secondWord.length())
return false;
//Default rule for setting to true if both strings are empty
if (firstWord.isEmpty() && secondWord.isEmpty())
return true;
if (firstWord.charAt(0) == secondWord.charAt(count))
return containedWordsCheck(firstWord.substring(1, firstWord.length()), secondWord, 0);
else if (firstWord.charAt(0) != secondWord.charAt(count) && count + 1 < secondWord.length())
return containedWordsCheck(firstWord, secondWord, count + 1);
else
return false;
Maybe my eyes are bad but I can't see where I am going out of bounds
Main for clarity:
public static void main(String[] args) {
String firstWord = userWord.nextLine();
String secondWord = userWord.nextLine();
int position = 0;
if (containedWordsCheck(firstWord, secondWord, position))
System.out.println("They are contained!");
else
System.out.println("They are not contained");