我正在编写这个程序来检查用户输入的单词是否是回文(该单词向后拼写时读起来相同)。我正在使用递归,正如我收到的任务所述。显然我的递归调用是正确的,因为参数每次都在变化。然而,我收到了 StackOverflow 错误。我无法确定错误的原因。有什么问题吗?
import java.util.Scanner;
public class PalindromeChecker {
static StringBuffer mainString, tempString, chString;
static int j = 0;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please input the String:");
mainString = new StringBuffer(input.nextLine());
tempString = mainString;
for(int n = 0; n < tempString.length(); n++){
if(tempString.charAt(n) == ' '){
tempString.deleteCharAt(n);
n -= 1;
}
}
chString = tempString;
tempString.reverse();
checker(j);
}
public static void checker(int k){
if(k < tempString.length()){
if(tempString.charAt(k) != chString.charAt(k)){
System.out.println("Not a Palindrome");
}
else
checker(j+1);
}
else
System.out.println("Palindrome Confirmed!");
}
}
最佳答案
据我所知,你从来没有改变过你的 j。因此每次 j = 1 时都会调用 checker。
编辑:StackOverFlowError 原因通常是因为您陷入了循环。
关于java - 堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44571514/