2013-02-26 61 views
1

我需要一些幫助,我正在做一個迴文檢測器做功課。我需要用戶輸入一個語句,多於一個單詞,程序需要檢測哪些單詞是迴文,哪些單詞不是。但是,我的循環中出現了一些問題,它只會檢測第一個單詞,然後將其他單詞混合在一起。我不確定我做錯了什麼。Palindromes在一個聲明:Java

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

我試圖解釋它在做什麼,我可以在程序中做到最好。

+1

您的代碼格式非常糟糕,使您的代碼非常難以閱讀。您之前在這裏提出過問題,所以您應該已經知道這一點,但是當向論壇發佈代碼時,如果您儘可能使代碼儘可能格式化和可讀,我們將非常感激。畢竟,你要求志願者閱讀,理解你的代碼並且幫助你,所以這真的不是要求太多。 – 2013-02-26 15:16:07

+0

你並沒有清除循環開始處的「reverse」。 – ogzd 2013-02-26 15:17:59

+1

經驗法則,它在日食,突出顯示,按Ctrl-Shift-f – david99world 2013-02-26 15:21:11

回答

2

您永遠不會重置循環內的「反向」值。因此,在第一個單詞之後,您只需添加更多字符來「倒轉」每次迭代。

reverse = ""; 

內部的主for循環

+2

補充:你在循環結束時清除變量詞,所以我認爲你剛剛把這兩個混在一起。用reverse =「」替換word =「」。 – flygoing 2013-02-26 15:23:53

+0

好的,我看到我做錯了,我認爲這是造成它的原始變量。謝謝一堆! :) – Dave555 2013-02-26 15:32:40

0

復位反向的值扭轉= 「」;就像你所做的一樣word =「」;