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.