So I'm doing this exercise on finding the next palindrome with only the use of the String class.
I kinda solved it, but had a question about something.
When I enter a String like 123456789, I get a java.lang.StackOverflowError. While when I enter a larger string like 9999999999999999999, I won't get the error. I did some research on this website and I think it has something to do with the recursive palindrome method I use.
Is there any way I could improve my code so it will handle bigger numbers? And why would 123456789 give an error and 9999999999999999999 not? The latter is bigger.
import java.io.*;
public class mainclass {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
System.out.println(palindroom(in.readLine()));
}
public static String increment(String str){
String incre="";
if(str.equals("9")){incre = "10";}
else{
switch(str.charAt(str.length()-1)){
case '0': incre = str.substring(0, str.length()-1)+"1";break;
case '1': incre = str.substring(0, str.length()-1)+"2";break;
case '2': incre = str.substring(0, str.length()-1)+"3";break;
case '3': incre = str.substring(0, str.length()-1)+"4";break;
case '4': incre = str.substring(0, str.length()-1)+"5";break;
case '5': incre = str.substring(0, str.length()-1)+"6";break;
case '6': incre = str.substring(0, str.length()-1)+"7";break;
case '7': incre = str.substring(0, str.length()-1)+"8";break;
case '8': incre = str.substring(0, str.length()-1)+"9";break;
case '9': incre = increment(str.substring(0, str.length()-1))+"0";break;
};
}
return incre;
}
public static String palindroom(String str){
String palin=increment(str);
boolean isPalindroom=true;
for(int i=0;i<palin.length();i++){
if(palin.charAt(i)==palin.charAt(palin.length()-i-1)){}
else{isPalindroom=false;}
}
if(isPalindroom){return palin;}
else{return palindroom(increment(str));}
}
}