/* * Author: CHEN Yongyuan (Walter) 1930006025 from OOP(1007) * Date: 2022-03-02 * Description: Test whether a sentence is a palindrome, iguore the case punctuation and spaces. * Assignment: #2 Question 3 */ import java.util.Scanner; public class TestPalindrome { public static void main(String[] args) { System.out.print("Enter a String: "); Scanner in = new Scanner(System.in); // read a line of input from the user String inStr = in.nextLine(); // close the scanner object in.close(); // convert the string to lower case String str = inStr.toLowerCase(); // remove all the punctuation using Character.isLetter() // str = str.replaceAll("[^a-zA-Z0-9]", ""); String str2 = str; str = ""; for (int i = 0; i < str2.length(); i++) { if (Character.isLetter(str2.charAt(i))) { str += str2.charAt(i); } } // reverse the string String reverse = new StringBuffer(str).reverse().toString(); // compare the two strings // if they are the same, the string is a palindrome // otherwise, it is not System.out.format("\"%s\" is %s a palindrome.\n", inStr, str.equals(reverse) ? "" : "not "); } }