I have been assigned to complete a palindrome program. However, I cannot use the charAt method.
Typically, I'd be able to solve this fairly quickly. However, since I cannot use charAt, I have no clue as to how I should go about doing this.
My idea is to take the length of the string, divide it by two (however this limits me to strings only with an even number of chars) then convert the substrings into int's and then finally compare the two int's.
This is my code thus far-
public static boolean isPal(String s)
{
int length = s.length();
int math = length / 2;
String side1 = s.substring(1,math);
String side2 = s.substring(math, length);
int s1 = Integer.parseInt(side1);
int s2 = Integer.parseInt(side2);
if(s1 == s2){
return true;
} else {
return false;
}
}
However, I have realized that this might not, and probably is not, the best way to handle the situation. I am currently running into this error-
Exception in thread "main" java.lang.NumberFormatException: For input string: "i"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Palindrome.isPal(Lab08st.java:47)
at Lab08st.main(Lab08st.java:20)
I believe it is because I need a for loop of sorts. However, having inadequate Java experience, I am unsure.
I am open to any and all suggestions. (So long as they do not require charAt)