通过逗号java在Array列表中分隔chars

时间:2012-12-02 19:53:55

标签: java arrays list arraylist char

  

可能重复:
  The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

除最后一个字符外,所有字符都应以逗号分隔 示例输出:“先前猜到的字符:a,b,c,x”或“猜到的上一个字符:a”

继承我所拥有的:

ArrayList<Character> charsGuessed = new ArrayList<Character>();

//takes in char guess from user
char guess=getCharacterGuess(in);

//adds char guessed to array
charsGuessed.add(guess);

int size=charsGuessed.size();
System.out.print("Previous characters guessed: ");

for(int i=0; i<size; i++)
{
   if(i<=size-1)
   {
      System.out.print(charsGuessed.get(i) + " ");
   }
   else
   {
      System.out.print("," + " " + charsGuessed.get(i));
   }
}

3 个答案:

答案 0 :(得分:1)

更好地使用StringBuilder

StringBuilder builder = new StringBuilder();
for (int i = 0; i < arraySize; i++){
    builder.append(charsGuessed.get(i));
    if (i < arraySize - 1){
        builder.append(", ");
    }
}
System.out.println(builder.toString());

答案 1 :(得分:1)

bellum's answer很好地涵盖了StringBuilder的用法。如果您恰好使用Guava,则可以使用Joiner

String charsGuessedConcat = Joiner.on(", ").join(charsGuessed);
System.out.print("Previous characters guessed: " + charsGuessedConcat);

答案 2 :(得分:0)

这非常简单。基本上,您希望在列表中的每个字符之后打印/附加逗号,但最后一个字符除外。

示例:

private static void printGuessedCharacters(List<Character> chars) {
    System.out.print("Characters guessed: ");

    if(chars.isEmpty()) {
        System.out.println("none.");
        return;
    }

    for(int i = 0; i < chars.size(); i++) {
        System.out.print(chars.get(i));

        if(i < chars.size() - 1) { // If it's not the last char in list.
            System.out.print(", ");
        }
    }
    System.out.println();
}

另外,如果您想要一个只包含唯一值的集合,您可以考虑使用HashSet而不是ArrayList。这将阻止您的程序多次打印出相同的字符。