Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method called printPalindrome that accepts a Scanner for the console as

ID: 3087211 • Letter: W

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"). If the following Scanner object were declared: Scanner console = new Scanner(System.in); printPalindrome(console); The resulting output for a call where the user types a palindrome would be: Type one or more words: racecar racecar is a palindrome! The output for a call where the user types a word that is not a palindrome would be: Type one or more words: hello hello is not a palindrome. For an added challenge, make the code case-insensitive, so that words like "Abba" and "Madam" will be considered palindromes. This is what I have so far... public static void printPalindrome (Scanner console) { System.out.print("Type one or more words: "); String word = console.nextLine(); word = word.toLowerCase(); String reverseWord = ""; for (int i = 0; i < word.length(); i++) { reverseWord += word.charAt(word.length()-1 -i); } if (reverseWord == word) { System.out.println(word + " is a palindrome!"); } else { System.out.println(word + " is not a palindrome."); } }

Explanation / Answer

First, your "if detection" check should be outside of your for loop. Second, you only need to loop through half the length of the word, because you are comparing outwards toward the center. Also, you could simplify the logic a little, and break from the loop as soon as you determine it is not a palindrome. Here is how I would solve it: public static void printPalindrome(Scanner console) { System.out.println("Word please! "); String s = console.next(); boolean isPalendrome = true; for (int i = 0; i
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote