简体   繁体   中英

StackOverflow Error

I am writing this program to check if the word which is entered by the user, is a Palindrome(the word reads the same when spelled backwards) or not. I am using recursion, as the task i was given stated so. Apparently my recursive call is correct, as the arguments are changing every time. Yet, i am getting the StackOverflow error. I can not identify the reason for the error. What is the problem?

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!");

    } 

}

From what I see you never change your j. So checker is called every time with j = 1.

Edit : StackOverFlowError reason is often because you are stuck in a loop.

Your troubles begin at the point where you are declaring all your variables as static . Thus, they are visible from all of your code, and all of your code can accidentally access them and modify them.

Your problem then continues with invoking checker(j+1); where instead you probably meant to do checker(k+1); , The static variable j is 0 and never changed, so j+1 will always be 1 . So, your function will always recurse.

J+1 means: (the value of the variable j) + 1. ++J or J++ means add one to the variable j.

the difference here is that when you do j+1 you never assign a new value to your variable J.

So if you need to increment j first do: checker(++j) j will be incremented and then passed to the checker method

If you need to pass j and then increment it do: checker(j++) . j will be pass to the checker method and then incremented

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM