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 に答える