我需要一些幫助,我正在做一個迴文檢測器做功課。我需要用戶輸入一個語句,多於一個單詞,程序需要檢測哪些單詞是迴文,哪些單詞不是。但是,我的循環中出現了一些問題,它只會檢測第一個單詞,然後將其他單詞混合在一起。我不確定我做錯了什麼。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);
}
}
我試圖解釋它在做什麼,我可以在程序中做到最好。
您的代碼格式非常糟糕,使您的代碼非常難以閱讀。您之前在這裏提出過問題,所以您應該已經知道這一點,但是當向論壇發佈代碼時,如果您儘可能使代碼儘可能格式化和可讀,我們將非常感激。畢竟,你要求志願者閱讀,理解你的代碼並且幫助你,所以這真的不是要求太多。 – 2013-02-26 15:16:07
你並沒有清除循環開始處的「reverse」。 – ogzd 2013-02-26 15:17:59
經驗法則,它在日食,突出顯示,按Ctrl-Shift-f – david99world 2013-02-26 15:21:11