Peebl Peebl - 3 months ago 15
Java Question

String manipulation for a shop interface?

I'm making a text based "shop" where the items are displayed like in most GUIs. Like this sort of:

| Item 1 | Item 2 | Item 3 |
| Item : price | Item:price | Item:price |
| Item weight | item weight | item weight |
| item 4 | item 5 | item 6 |

All items created use the same print function, with exception to Swords which will have a dmg print aswell, but nothing special.

public void print()
System.out.println("# -Name of item: " + itemName + "-");
System.out.println("# Item description: " + desc);
System.out.println("# Item value: " + value + " gold");
System.out.println("# Item weight: " + weight + "kg");
System.out.println("# Item action: " + action);

Where they get their values from somewhere else, now I understand that i can't just do print(), print(),print(); and they'll be next to each other. My main concern is creating the boxes the items are displayed in at the exact same places each time, and have all text inside wrapped around the inside of the box given that description is sometimes rather long. I do have a description modifying class I probably could use to make that fit however. I got the replaceall part from someone else though, so I'm not too familiar with the "coding" of that.

public String formatDesc(String desc)
desc = "\n#\t" + desc;
desc += "\n"; // Needed to handle last line correctly
desc = desc.replaceAll("(.{1,30})\\s+", "$1\n#\t");
return desc;


In order to get the boxes placed right I would find out the maximum length all items in each column. If I´m now printing item1 I would look the length of the printed String and calculated the missing spaces up to the maximum so:

int max_column1=//initialized via maximum length all items in each column

int difference=max_column1-print().length()

and print spaces for that difference. And after that the '|'

Or your formatDesc() method could make a line break at the maximum specified column width.