Dave555
Dave555

Reputation: 167

Palindromes in a Statement: Java

I need some help with a palindrome detector that I am doing for homework. I need the user to enter a statement, so more then one word, and the program needs to detect which words are a palindrome and which ones are not. However, something in my loop is going wrong in that, it will only detect the first word then blend the others after together. I'm not sure what I'm doing wrong.

import javax.swing.JOptionPane;

public class Main {
   static int numpali = 0;

   public static void main(String[] args) {
      // ask the user to enter a statement
      String statement = JOptionPane.showInputDialog("Enter a Statement");
      String reverse = "";
      // Array to split the sentence
      String[] words = statement.split(" ");

      // Run a loop to seperate the words in the statement into single Strings
      for (String word : words) {
         // Print out original word
         System.out.println(word + "\n");
         int wordlength = word.length();
         // send the word to lowercase so capitals are negligible
         String wordlower = word.toLowerCase();

         // Run a loop that reverses each individual word to see if its a
         // palindrome
         for (int t = wordlength; t > 0; t--) {
            reverse += wordlower.substring(t - 1, wordlength);
            wordlength--;
         }
         System.out.println(reverse);
         // show a message if the word is a palindrome or not, and add 1 to the
         // total number of palindromes
         if (reverse.equals(wordlower)) {
            JOptionPane.showMessageDialog(null, word + " is a Palindrome!");
            numpali = numpali + 1;
         }
         word = "";
      }
      System.out.println("Number of Palindromes:" + "\n" + numpali);
   }
}

I've tried to explain what its doing the best I can inside the program.

Upvotes: 1

Views: 1146

Answers (2)

Pradeep K M
Pradeep K M

Reputation: 1481

Reset the value of reverse to reverse=""; just like what you have done word="";

Upvotes: 0

Louis Ricci
Louis Ricci

Reputation: 21086

You never reset the "reverse" value inside your loop. So after the first word your just adding more characters to "reverse" every iteration.

Put

reverse = "";

inside your main for loop

Upvotes: 2

Related Questions