I need help I have tried looking up many methods but can't seem to get it to work. I need this to not recognize white space, so if the user inputs le vel , it should say ,"Yes it is a Palindrome", just like if it was level //with no whitespace. The user input needs to end with a period and the program should not take into account the period. So level. should return true.
import java.util.Scanner;
public class PalindromeDemo
{
public static void main(String[] args)
{
String phrase, answer;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println("I will determine if a string is a palindrome");
System.out.println("Enter a word or characters and end it with a period");
phrase = keyboard.nextLine();
Palindrome pd = new Palindrome();
if(pd.checkPalindrome(phrase))
System.out.println("YES, the phrase is palindrome!");
else
System.out.println("NO, the phrase is NOT palindrome.");
System.out.println();
System.out.println("Would you like to continue? Enter yes or no");
answer = keyboard.nextLine();
System.out.println();
}
while(answer.equalsIgnoreCase("yes"));
}
}
public class Palindrome
{
public static final int MAX_CHARS = 80;
public boolean checkPalindrome(String text)
{
char[] array = new char[80];
int length = text.length();
String reverseText = "";
for(int i = length-1; i >= 0; i--)
{
reverseText = reverseText + text.charAt(i);
}
if(reverseText.equalsIgnoreCase(text))
{
return true;
}
else
{
return false;
}
}
}
Use this method:
public boolean checkPalindrome(String text) {
// remove all whitespace from input word (do this FIRST)
text = text.replaceAll("\\s+", "");
// remove optional period from end of input word
if (text.endsWith(".")) {
text = text.substring(0, text.length() - 1);
}
char[] array = new char[80];
int length = text.length();
String reverseText = "";
for (int i = length-1; i >= 0; i--) {
reverseText = reverseText + text.charAt(i);
}
if (reverseText.equalsIgnoreCase(text)) {
return true;
}
else {
return false;
}
}