Home > other >  How can I print the special character but still I can compare it if its a palindrome or not
How can I print the special character but still I can compare it if its a palindrome or not

Time:05-05

import java.util.*;
public class Fin4 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter a word to check if it is a palindrome: ");
        String word = in.nextLine();
        
        word = word.replaceAll("[{}!@#$%^&.,' ]", "");
        word = word.substring(0);
        String reverse = "";
        for(int i=word.length()-1;i>=0;i--)
            reverse =word.charAt(i);
            
        if(word.equalsIgnoreCase(reverse))
            System.out.print(word   " is a palindrome.");
        else
            System.out.print(word   " is not a palindrome.");
    }
}

For example Enter a word to check if it is a palindrome: Madam, I'm adam The output should be -> Madam, I'm adam is a palindrome but my output is -> MadamImadam is a palindrome

CodePudding user response:

You can store the copy of the original word in a variable ( say copyWord) and print that variable in the print statements.

The reason why the original string is not getting printed is because you are modifying it and storing the updated word( in word.replaceAll())

public class Fin4 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a word to check if it is a palindrome: ");
        String word = in.nextLine();
        String copyWord = word;
        word = word.replaceAll("[{}!@#$%^&.,' ]", "");
        word = word.substring(0);
        String reverse = "";
        for (int i = word.length() - 1; i >= 0; i--)
            reverse  = word.charAt(i);

        if (word.equalsIgnoreCase(reverse))
            System.out.print(copyWord   " is a palindrome.");
        else
            System.out.print(copyWord   " is not a palindrome.");
    }
}

and the output is

Enter a word to check if it is a palindrome: Madam, I'm adam
Madam, I'm adam is a palindrome.
  • Related