Java Reference
In-Depth Information
Note that some palindromes have an even number of characters, whereas oth-
ers have an odd number of characters. The PalindromeTester program shown
in Listing 5.9 tests to see whether a string is a palindrome. The user may test as
many strings as desired.
The code for PalindromeTester contains two loops, one inside the other.
The outer loop controls how many strings are tested, and the inner loop scans
LISTING 5.9
//********************************************************************
// PalindromeTester.java Author: Lewis/Loftus
//
// Demonstrates the use of nested while loops.
//********************************************************************
import java.util.Scanner;
public class PalindromeTester
{
//-----------------------------------------------------------------
// Tests strings to see if they are palindromes.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome:");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while (str.charAt(left) == str.charAt(right) && left < right)
{
left++;
right--;
}
System.out.println();
Search WWH ::




Custom Search