1

Possible Duplicate:
The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

All the chars should be separated by a comma except for the last char.
Example output: "Previous characters guessed: a, b, c, x" or "Previous characters guessed: a"

Heres what I have:

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));
   }
}
Community
  • 1
  • 1
  • http://stackoverflow.com/questions/205555/the-most-sophisticated-way-for-creating-comma-separated-strings-from-a-collectio might help – andyb Dec 02 '12 at 19:59
  • You should improve details of your questions. So one line ... really? – MUG4N Dec 08 '12 at 18:46

3 Answers3

1

Use StringBuilder better:

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());
MUG4N
  • 19,377
  • 11
  • 56
  • 83
bellum
  • 3,642
  • 1
  • 17
  • 22
1

bellum's answer covered the use of StringBuilder well. If you happen to be using Guava, you can use Joiner:

String charsGuessedConcat = Joiner.on(", ").join(charsGuessed);
System.out.print("Previous characters guessed: " + charsGuessedConcat);
Community
  • 1
  • 1
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
0

This is very straightforward. Basically, you want to print/append a comma after every character in the list except for the last one.

Example:

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

On a side note, if you want a collection that only holds unique values, you can look into using a HashSet rather than an ArrayList. This will prevent your program from printing out the same character more than once.

Phil K
  • 4,939
  • 6
  • 31
  • 56