Monday, April 21, 2014

Java program to check if a word is a Palindrome with user input from console

In this program we would be making the user of BufferedReader to get the input from the user and then it would be saved in String 's'. After that we would be comparing the words from first to last to check if the word is a Palindrome. It works for both even and odd number of digits as the in case of odd number of digits the middle digit is ignored. There are some complex methods to shorten the code but if you are starting out then you should try this easy code.

package palindrome;
/**
 *
 * @author ankit
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Comp
{int counter=0; String s;
    Comp()
    {
        System.out.println("Enter the name");
        try{
            BufferedReader bufferRead= new BufferedReader(new InputStreamReader(System.in));
             s= bufferRead.readLine();
            for(int i=0;i<s.length();i++) {
            if( s.charAt(i) != '$' ) {
        counter=counter+1;
    }
            }           
        }
        catch(IOException e)
        {System.out.println(e);}
       
    }
    int calc()
            {int a=0;
            for (int i=0;i<=(counter-1)/2;i++)
            { if(s.charAt(i)!=s.charAt(counter-i-1))
                a=a+1;
            }
            return a;
            }
}
public class Input {
  public static void main(String[] args) {

        Comp in= new Comp();
        int x;
        x=in.calc();
 if (x==0)
            System.out.println("It is Palindrome");
        else
            System.out.println("Not a palindrome");
  }
}

No comments:

Post a Comment