2017-02-15 10 views
-2

Я создаю программу, которая берет две строки, а затем сравнивает их, чтобы определить, содержатся ли символы первой строки во второй строке (в порядке).Рекурсивный метод: StringIndexOutOfBoundsException

Я использовал кол-целое число, чтобы отслеживать положение

К сожалению, я получаю StringIndexOutOfBoundsException: String index out of range: 0 при выполнении основной и входящих в «Эльф» для первого слова, и «я» для второго, например.

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; 

Может быть, мои глаза плохо, но я не могу видеть, куда я иду за пределы

Главное для ясности:

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"); 
+0

Какая линия бросает исключение? – azurefrog

+0

Используйте регулярное выражение, чтобы найти совпадение. Это будет намного проще – user1211

+0

Просьба предоставить полную функцию и как вы ее вызываете для ясности – Sangharsh

ответ

0

Возврат, если count равно длине от secondWord

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() || count == 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; 
0

Th e указывает, что вы пытаетесь выполнить charAt на пустой строке. Пустая строка не имеет индекса 0, так как она пуста. Просто добавьте проверку, чтобы остановить, если строка пуста:

public static boolean containedWordsCheck(String firstWord, String secondWord, int count) { 
    if (firstWord.length == 0) 
     return false; 
    //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; 
} 
+0

Спасибо за исправление исключения, к сожалению, похоже, что мой код не работает. –