Home

Example Application: Finding a Palindrome

 

Introduction

A palindrome is a word or a sentence that reads the same way from left to right or from right to left.

This is an example code of finding out whether a word or sentence is a palindrome. This code uses iteration:

/* File:       Exercise.java
 * Author:     
 * Date:       Friday, March 06, 2009
 * Class:      CMSC 230
 * Purpose:    This application is used to determine whether s string
 *             is a palindrome
 */

package Palindrome1;
import java.util.Scanner;

public class Main {
    // This method uses an iterative to analyze a string
    // and find out whether it is a palindrome
    private static boolean iterative(String strSubmitted) {
        int fromLeft;
        boolean result = false;
        int fromRight = strSubmitted.length() - 1;
        
        if(strSubmitted.length() == 1)
            result = true;
        else {
            for(fromLeft = 0;
                fromLeft < strSubmitted.length();
                fromLeft++, fromRight--) {
                if(strSubmitted.charAt(fromLeft) ==
                        strSubmitted.charAt(fromRight)) {
                    result = true;
                }
                else
                    result = false;
            }
        }
        
        return result;
    }
    
    public static void main(String[] args) {
        // This variable will be used to hold the result of a method
        boolean is = false;
        // This is the value the user will enter
        String sentence = "";
        // A Scanner object will be used to request a value from the user
        Scanner scnr = new Scanner(System.in);
        
        // Request a string from the user
        System.out.print("Enter a word or a sentence: ");
        sentence = scnr.nextLine();
        is = iterative(sentence.toLowerCase());
        
        // Find out whether the user-entered string was a palindrome
        // Display the result accordingly
        if(is == true)
            System.out.println(sentence + " is a palindrome.");
        else
            System.out.println(sentence + " is not a palindrome.");
        
    }
}

 

 
 
 
 
 

Home Copyright © 2009-2016, FunctionX, Inc.