I’m having some trouble with a question from my programming II class and have hit a brick wall, was wondering if someone could help?
The question asks for a user to input a string, the program to reverse the input string and then to compare the reverse to the original, this must be done recursively.
So far I have:
public class question1
{
public static void main(String args[])
{
String input = JOptionPane.showInputDialog(null, "Please enter a sentence to determine if it is a palindrome.");
String backwardsinput = Reverse(input);
System.out.println(backwardsinput);
boolean Palindrome = PalindromeCheck(backwardsinput, input);
if (Palindrome == true)
{
JOptionPane.showMessageDialog(null,"That is a palindrome!");
}
if (Palindrome == false)
{
JOptionPane.showMessageDialog(null,"That is not a palindrome");
}
}
public static String Reverse (String input)
{
if (input.length() <= 1)
return input;
else
{
char x = input.charAt(input.length()-1);
return x+Reverse(input.substring(0,input.length()-1));
}
}
public static boolean PalindromeCheck (String backwardsinput, String input)
{
if(input.length() == 0 || input.length() == 1)
return true;
if(backwardsinput.charAt(0) == input.charAt(input.length()-1))
return PalindromeCheck(backwardsinput.substring(1, backwardsinput.length()-1), input.substring(1, input.length()-1));
else
return false;
}
}
My problem is, it tells me everything is a palindrome, I’ve looked at it over and over and can’t figure out why!
You’re doing the work twice (sort of).
should be
You almost got it 🙂
Also, another way of expressing
is
thus your last lines could be written as
Related question / answer: