Search code examples
javastring-formattingstringbuilder

Can I format an unknown amount of strings comma separated with three strings on each line?


I have looked for the past hour at least but to no avail. I'm writing a text based adventure game and I have an ArrayList storing my inventory. I am currently working on a "displayInventory" method which simply prints the inventory to console.

public void displayInventory()  
{                   
    
    StringBuilder result = new StringBuilder("Inventory: \n");


    String format = ("%s, %s, %s %n"); 
    
    for (int i=0; i< inventory.size(); i++)
    {
        
        result.append(inventory.get(i));
    }
        
    //String result = String.join("," inventory);
    
    
    System.out.format(format, result.toString());;
} 

Now initially my issue was figuring out how to use it with StringBuilder but now I sort of have that down. But I've run into the issue where I've set the format to three strings(items from inventory) to be printed to each line. After testing it with only two items I get the errors below (which makes sense).

Inventory: 
Small BottleLarge Bottle, Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s'
at java.base/java.util.Formatter.format(Formatter.java:2688)
at java.base/java.io.PrintStream.format(PrintStream.java:1209)
at wonderland/gameObjects.Player.displayInventory(Player.java:41)
at wonderland/gameObjects.Test.main(Test.java:19)

Do I need to set up some sort of check to see if there is a multiple of three items in the players inventory and have different print statements/formats if not? Is there a way to format an unknown amount (or at least a varying amount) of strings?

The player could pick three items up, use one, then pick up another two. I need some way of displaying the varying amount of items that could be in their inventory.

I hate asking questions on SO because they almost always get declared duplicates, despite no case being identical. So I was really hesitant but couldn't take the head trauma any longer. Thank you in advance for any and all help/answers.


Solution

  • Using the String.join() you describe in the comments, you get this:

    List<String> inventory = List.of(
        "A", "B", "C", "D", "E", "F", "G", "H", "I",
        "J", "K", "L", "M", "N", "O", "P", "Q");
    
    public void displayInventory()  {                   
        System.out.println("Inventory:");
        for (int i = 0, size = inventory.size(); i < size; i += 3)
            System.out.println(String.join(", ",
                inventory.subList(i, Math.min(i + 3, size))));
    } 
    

    and

    displayInentory();
    

    output:

    Inventory:
    A, B, C
    D, E, F
    G, H, I
    J, K, L
    M, N, O
    P, Q