我需要一些帮助,我正在做一个回文检测器做功课。我需要用户输入一个语句,多于一个单词,程序需要检测哪些单词是回文,哪些单词不是。但是,我的循环中出现了一些问题,它只会检测第一个单词,然后将其他单词混合在一起。我不确定我做错了什么。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