我在java中有一个程序,当你输入一个句子时,程序会告诉你有多少回文单词并输出单词。但是,当我输出单词时,我似乎无法在每次输出后得到逗号。例如,如果我输入“Abba正在运行到雷达”它输出有2个回文并且回文是“ Abba雷达”。然而,我希望它输出回文“阿巴,雷达”。无论我怎么做,我都可以得到“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.");
}
}
}
答案 0 :(得分:1)
只需将您的代码修改为:
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);
答案 1 :(得分:0)
代码也可以是
if (newWord[i].toLowerCase().equals(result.toLowerCase())) {
count++;
if (count > 1)
{
palindromeWords += ", ";
}
palindromeWords += newWord[i];
}
答案 2 :(得分:0)
在发现第一个单词之后,逗号位于新单词之前...
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.");
}
}
所以我将palindromewords更改为StringBuffer并在追加操作后移动count ++。希望这有帮助!