0

I have got a little problem with printing out comma in my java project. In forEach section the program is always printing out "," > even after the last word... see output

.listener("lookAround", (Game g, String action, AbstractGameObject object, Object retVal) -> {
    System.out.print("You see: \n\t");

    if (g.getItemsInRoom((Room) object).isEmpty() && g.getDoorsInRoom((Room) object).isEmpty())
       System.out.print("nothing");

    g.getItemsInRoom((Room) object)
                     .stream()
                     .forEach(item -> System.out.print(item.getName() + ", "));

    g.getDoorsInRoom((Room) object)
                     .stream()
                     .forEach(door -> System.out.print(door.getName() + ", "));
    System.out.println("\n");
})

The output:

You see:    
Black Wooden door, Brown Wooden door,

I would like output:

You see:    
Black Wooden door, Brown Wooden door

Is there a easy way to solve this problem ? Thank you for a help :)

0

2 Answers 2

3

I don't think you should be printing inside that forEach lambda. Actually I'm not even sure you should be using the stream API there.

Think about using String.join() or the StringJoiner class instead.

Sign up to request clarification or add additional context in comments.

Comments

1

Using a StringJoiner directly, rather than via the Stream API, let’s you handle the empty case without additional code:

StringJoiner j=new StringJoiner(", ").setEmptyValue("nothing");
g.getItemsInRoom((Room)object).forEach(o -> j.add(o.getName()));
g.getDoorsInRoom((Room)object).forEach(o -> j.add(o.getName()));
System.out.println("You see: \n\t"+j);

1 Comment

Thank you very much, your solution helped a lot :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.