我正在创建一个程序,它接受两个字符串,然后比较两个字符串以确定第一个字符串的字符是否包含在第二个字符串中(无序)。递归方法: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");
什么是抛出异常? – azurefrog
使用正则表达式来查找模式匹配。它会简单得多 – user1211
请提供完整的功能以及如何清晰地调用它 – Sangharsh