1

我需要一些关于我正在为家庭作业做的回文检测器的帮助。我需要用户输入一个语句,所以不止一个词,程序需要检测哪些词是回文,哪些不是。但是,我的循环中出现了问题,它只会检测到第一个单词,然后将其他单词混合在一起。我不确定我做错了什么。

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);
   }
}

我试图解释它在程序中尽我所能。

4

2 回答 2

2

您永远不会重置循环内的“反向”值。因此,在第一个单词之后,您只需添加更多字符来“反转”每次迭代。

reverse = "";

在你的主 for 循环内

于 2013-02-26T15:19:47.583 回答
0

将 reverse 的值重置为 reverse=""; 就像你所做的那样 word="";

于 2013-02-26T15:39:41.290 回答