我在Java中有一个程序,当您输入一个句子时,该程序会告诉您有多少回文词并输出。但是,当我输出单词时,每次输出后似乎都不会出现逗号。例如,如果我输入“ Abba正在运行到雷达”,则输出存在2个回文,而回文是“ Abba雷达”。但是我希望它将回文输出为“ Abba,Radar”。无论我怎么做,我都可以获取“ Abba Radar”或“ Abba,Radar”。任何帮助,将不胜感激。

代码

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

最佳答案

只需将代码修改为:

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

09-11 18:54