该代码适用于长度为 6 的单词。但是当我输入一个 7 个字母的单词时,它会抛出这个堆栈溢出错误。有没有办法解决这个问题?在这段代码中,生成器函数将单词的“第 i 个”元素与最后一个元素交换。example->car . 在第一遍中,它将生成'rac',在第二遍中将生成'cra'。现在这两个新单词作为参数传递给'check'函数。需要注意的是,当第一次调用“生成器”函数时,输入的单词会被添加到数组列表中。此后,当且仅当该词不存在于数组列表中时,才将词添加到数组列表中,即仅当生成新词时才调用生成器函数。所以现在,生成了 'rac' 并传递给 'check',它返回 false。这意味着该词不存在并且调用了生成器函数。现在'rac'生成'car'和'rca'但是'car'已经存在。因此它不会作为参数传递给“生成器”函数。arraylist 中存在的单词作为终止条件。
import java.util.*;
import java.io.*;
class progx
{
static ArrayList<String> word = new ArrayList<String>();
public static void main(String[] args) throws IOException
{
progx ob = new progx();
ob.input();
}
void input() throws IOException // this function takes the input
{ // from user and calls "generator" function
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter word");
String s = in.readLine();
progx obj = new progx();
obj.generator(s); // call 'generator' function
}
void generator(String s) throws IOException
{
progx ob = new progx();
String output = "";
boolean c = false;
word.add(s); // adds the word to arraylist
int i, j, l = s.length(), l2 = l - 1;
char temp;
char[] b = new char[l];
for (i = 0; i < l; i++)
{
b[i] = s.charAt(i); // initializing each element in array
} // with the ith character of the input string
i = 0; // re-initializing 'i' for the while loop
while (i < l)
{
temp = b[i]; // swapping ith character with last element
b[i] = b[l2];
b[l2] = temp;
output = (ob.convertArray(b));// storing the new word in 'output'
c = ob.check(output);// checking whether the elemnt is present in
// arraylist
if (c == false)// if the word is not present, then call the 'generator'
// function
{
System.out.println(output);
ob.generator(output);
}
for (j = 0; j < l; j++) // re-initialising the array as the swapping
{
b[j] = s.charAt(j);
} // might change the position characters
i++; // of the original input String "s"
}
}
String convertArray(char[] s) // array converter- converts array to string
{
String n = "";
for (int i = 0; i < s.length; i++)
{
n = n + s[i];
}
return n;
}
boolean check(String output) // function that checks presence
{ // of the generated word in the array
boolean present = word.contains(output);
return present;
}
}