Question:
How can you test a string to see if it is a palidrome?
Answer:
By comparing the string with a 2nd string created by the method StringBuilder().reverse().
Code:
import java.util.*; public class Palidrome { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter exit to quit."); while(true){ System.out.print("Enter a word: "); String str = sc.nextLine(); if(str.equals("exit")){ break; } String reverse = new StringBuilder(str).reverse().toString(); if (str.toLowerCase().compareTo(reverse.toLowerCase()) == 0) { System.out.println(str + " is a palidrome"); } else { System.out.println(str + " is not a palidrome"); } } sc.close(); } }
Output:
$ java Palidrome Enter exit to quit. Enter a word: hello hello is not a palidrome Enter a word: racecar racecar is a palidrome Enter a word: Racecar Racecar is a palidrome Enter a word: exit