我需要帮助我做家庭作业的回文探测器。我需要用户输入一个语句,所以多于一个单词,程序需要检测哪些单词是回文,哪些不是。但是,我的循环中的某些内容出错了,它只会检测到第一个单词,然后将其他单词混合在一起。我不确定我做错了什么。
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);
}
}
我试图解释它在程序中做得最好的事情。
答案 0 :(得分:2)
您永远不会重置循环内的“反向”值。因此,在第一个单词之后,您只需添加更多字符以“反转”每次迭代。
把
reverse = "";
在你的主要for循环中
答案 1 :(得分:0)
将reverse的值重置为reverse =“”;就像你所做的一样word =“”;