我在java中有一个程序,当你输入一个句子,程序告诉你有多少回文单词,并输出这些单词。然而,当我输出单词时,我似乎无法在每个输出之后得到一个逗号。例如,如果我输入"Abba正在运行到该雷达“,它会输出有2个回文,回文是"Abba雷达”。不过,我希望它输出回文为"Abba,雷达“。无论我怎么做,我都可以得到“阿巴雷达”或“阿巴,雷达”。任何帮助都将不胜感激。
密码
package strings;
import javax.swing.*;
public class Palindrome2 {
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Words that are the same forwards and backwards are called palindromes.\nThis program determines if the words are palindromes.\n\nEnter a sentence(do not include a punctuation mark):");
String newWord[] = word.split(" ");
String palindromeWords = "";
int count = 0;
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
palindromeWords = palindromeWords + " " + newWord[i];
}
}
JOptionPane.showMessageDialog(null, "There are " + count + " palindromes in this sentence");
if (count != 0) {
JOptionPane.showMessageDialog(null, "The palindromes are:\n" + palindromeWords);
} else {
JOptionPane.showMessageDialog(null, "There isn't any palindromes.");
}
}
}发布于 2014-02-25 00:36:46
只需将代码修改为:
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
palindromeWords = palindromeWords + newWord[i] + ",";
}
}在for循环之后,删除最后一个逗号的substring:
palindromeWords = palindromeWords.substring(0,palindromeWords.length()-1);发布于 2014-02-25 00:39:03
代码也可以是
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
if (count > 1)
{
palindromeWords += ", ";
}
palindromeWords += newWord[i];
}发布于 2014-02-25 00:54:13
第一个词被发现后,逗号在新词之前.
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Words that are the same forwards and backwards are called palindromes.\nThis program determines if the words are palindromes.\n\nEnter a sentence(do not include a punctuation mark):");
String newWord[] = word.split(" ");
StringBuffer palindromeWords = new StringBuffer();
int count = 0;
for (int i = 0; i < newWord.length; i++) {
String result = new StringBuffer(newWord[i]).reverse().toString();
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
if (count > 0) {
palindromeWords.append(",");
}
palindromeWords.append(newWord[i]);
count++;
}
}
JOptionPane.showMessageDialog(null, "There are " + count + " palindromes in this sentence");
if (count != 0) {
JOptionPane.showMessageDialog(null, "The palindromes are:\n" + palindromeWords.toString());
} else {
JOptionPane.showMessageDialog(null, "There isn't any palindromes.");
}
}因此,我将回文单词修改为StringBuffer,并在追加操作后移动count++。希望这能有所帮助!
https://stackoverflow.com/questions/22002188
复制相似问题