//******************************************************************** // PalindromeTester.java Author: Lewis and Loftus // modified: Omar // Demonstrates the use of nested while loops. // StringTokenizer class is used to consider string with spaces //******************************************************************** import cs1.Keyboard; import java.util.StringTokenizer; public class PalindromeTester1 { //----------------------------------------------------------------- // Tests strings to see if they are palindromes. //----------------------------------------------------------------- public static void main (String[] args) { String str, another = "y"; int left, right; while (another.equalsIgnoreCase("y")) // allows y or Y, you may use equals twice { System.out.println ("Enter a potential palindrome:"); str = Keyboard.readString(); // this part is added to accept strings with spaces // StringTokenizer is used to remove the spaces String noSpaceStr = ""; str = str.toLowerCase(); // ignore cases of the compared characters StringTokenizer t = new StringTokenizer(str); while(t.hasMoreTokens()) { noSpaceStr += t.nextToken(); } str = noSpaceStr; //--------------------------------------- left = 0; right = str.length() - 1; while (str.charAt(left) == str.charAt(right) && left < right) { left++; right--; } System.out.println(); if (left < right) System.out.println ("That string is NOT a palindrome."); else System.out.println ("That string IS a palindrome."); System.out.println(); System.out.print ("Test another palindrome (y/n)? "); another = Keyboard.readString(); } } }