62.3k views
5 votes
Write a modular program that allows the user to enter a word or phrase and determines whether the word or phrase is a palindrome. A palindrome is a word or phrase that reads the same backwards as forwards. Examples include: civic, kayak, mom, noon, racecar, Never odd or even., and Was it a Rat I saw

1 Answer

4 votes

Answer:

import java.util.Scanner;

public class num10 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("Enter a word");

String word = in.nextLine();

String reversed = "";

//Get the length of the string entered

int length = word.length();

//Loop through the string and reverse th string

for ( int i = length - 1; i >= 0; i-- )

reversed = reversed + word.charAt(i);

//Compare the two strings "word" and "reversed"

if (word.equals(reversed))

System.out.println(word+" is a palindrome");

else

System.out.println(word+" is not a palindrome");

}

}

Step-by-step explanation:

Since we know that a palindrome word is a word that reads the same forward and backward, The Idea here is:

  • To obtain a word from a user.
  • Use a for loop to reverse the word and store in another variable
  • Use if....else to compare the two strings and determine if they are equal, if they are equal then the word is palindrome.
User Debarchito
by
6.8k points