In: Computer Science
Input a phrase from the keyboard and output whether or not it is a palindrome.
For example:
1. If the input is
Madam I'm Adam
Your output should be
"Madam, I'm Adam" is a palindrome
2. If your input is
Going to the movies?
Your output should be
"Going to the movies?" is not a palindrome
Note the quotes in the output line.
Code language java using JGrasp
Program to check whether string is Palindrome or not:
Code and Screenshots are attached.
Note: Output in double quotes is important, we need to insert comma after first word if entered string is palindrome.
import java.util.*;
public class Palindrome
{
// To check sentence is palindrome or not
static boolean checkPalindrome(String str)
{
int fromStart = 0;
int fromEnd = str.length()-1;
// Lowercase string
str = str.toLowerCase();
// Compares character until they are equal
while(fromStart <= fromEnd)
{
char getAtStart = str.charAt(fromStart);
char getAtEnd = str.charAt(fromEnd);
if (!(getAtStart >= 'a' && getAtEnd <= 'z'))
fromStart++;
else if(!(getAtEnd >= 'a' && getAtEnd <= 'z'))
fromEnd--;
// If characters are equal
else if( getAtStart == getAtEnd)
{
fromStart++;
fromEnd--;
}
// If characters are not equal then sentence is not a palindrome
else
return false;
}
// Returns true if sentence is palindrome
return true;
}
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream.
System.out.print("Enter a string to check whether it is a Palindrome: ");
String str= sc.nextLine();
if( checkPalindrome(str)){
if(str.contains(" ")){
String firstWord= null;
firstWord= str.substring(0, str.indexOf(" "));
System.out.println("\""+firstWord+ ","+str.substring((firstWord.length()+1), str.length())+"\""+" is a palindrome");
}}
else
System.out.println("\""+ str+ "\"" +
" is not a palindrome");
}
}
Screenshots