SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Exercises
Question:13 | ISBN:9780136091813 | Edition: 2

Question

Write a method called printPalindrome that accepts a Scanner for the console as a parameter, and prompts the user to enter one or more words and prints whether the entered String is a palindrome (i.e., reads the same forwards as it does backwards, like "abba" or "racecar").
For an added challenge, make the code case-insensitive, so that words like “Abba” and “Madam” will be considered palindromes.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer


import java.util.Scanner;

public class PalindromeCheck {
	
	
	// below method check whether the string is palindrom or not and also return true if 
	// it is palindrome.
	public static boolean printPalindrome() {
		 System.out.print("enter a string: ");
		 
		 // takes inpur from the console
		 Scanner input = new Scanner(System.in);
		    String str = input.nextLine();
		    // make it lowercase make the functions independent of case
		    String var = str.toLowerCase();
		    int i = 0;
		    int j = str.length() - 1;
		    boolean flag = false;
		    
		    // this loop continours as long as i < j
		    while(i < j) {
		        if(var.charAt(i) != var.charAt(j)) {
		            System.out.println("the string is not a palindrome");
		            return flag;
		        }
		        i++;
		        j--;
		    }
		    
		    System.out.println("the string is a palindrome");
		    input.close();
		    flag = true;
		    return flag;
		  
	}
	

	public static void main(String[] args) {
		
		PalindromeCheck.printPalindrome();
		

	}

}
Output:


enter a string: madam
the string is a palindrome

 

0 0

Discussions

Post the discussion to improve the above solution.