/* Solution to Programming Lab 5 by Craig Persiko - CS 111A
Lab6Palindrome.java - Palindrome Program
*/
import java.util.Scanner;
public class Lab6Palindrome
{
public static void main(String[] args)
{
String word = getWord();
System.out.print("The word you entered, '" + word);
if (is_palindrome(word))
System.out.println("' is a palindrome.");
else
System.out.println("' is not a palindrome.");
}
// Input the word from the user
static String getWord()
{
Scanner keyIn = new Scanner(System.in);
System.out.print("Please enter a word: ");
return keyIn.nextLine();
}
// Returns true if w is a palindrome,
// false if not.
static boolean is_palindrome(String w)
{
int len = w.length();
int index_of_last = len - 1;
// only first half of string needs to be checked
// (since we're comparing it to the second half)
// If string length is odd, we can ignore middle character
// (integer division handles this correctly)
for (int i=0; i<len/2; i++) // here we WANT integer division -> integer result
if (w.charAt(i) != w.charAt(index_of_last - i))
return false; // not a palindrome
return true; // Every letter was reflected
}
}
/* Sample output:
[cpersiko@fog cs111a]$ java Lab6Palindrome
Please enter a word: radar
The word you entered, 'radar' is a palindrome.
[cpersiko@fog cs111a]$ java Lab6Palindrome
Please enter a word: abccba
The word you entered, 'abccba' is a palindrome.
[cpersiko@fog cs111a]$ java Lab6Palindrome
Please enter a word: abcddxba
The word you entered, 'abcddxba' is not a palindrome.
[cpersiko@fog cs111a]$
*/
syntax highlighted by Code2HTML, v. 0.9