java - 堆栈溢出错误

标签 java recursion stack-overflow palindrome

我正在编写这个程序来检查用户输入的单词是否是回文(该单词向后拼写时读起来相同)。我正在使用递归,正如我收到的任务所述。显然我的递归调用是正确的,因为参数每次都在变化。然而,我收到了 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/

相关文章:

visual-studio-2010 - C 函数调用中的堆栈溢出 - MS Visual C++ 2010 Express

java - Maven:系统范围依赖的NoClassDefFoundError

java - 通过其 API 设置 BIRT 数据源

c - 递归函数的内联

java - 遵循递归

exception - window : avoid pushing full x86 context on stack

java - 使用 Oracle PL/SQL 扩充 zip 流

java 从 Stream<Integer> 创建二维数组

c++ - 在不使用 for 或 while 的情况下在排序数组中查找元素

c# - 用于 TCP 监听的线程抛出 StackoverflowException