I'm trying to create a menu-like text in the Terminal using Java. I need it to look roughly like this:
I'm doing this using a printf method that looks like this:
System.out.printf("%d Pygmy Puffs at %d Knuts ea.: d %n", pygmy_ordered, pygmy, pygmy_total);
System.out.printf("%d bags of Extendable ears at %d Knuts ea.: d %n", extendable_ears_three_ordered, extendable_ears_three, extendable_ears_three_total);
However, this creates a result where the total for the items (last number) is an uneven amount of space away from the rest of the text line to line.
How would I go about fixing this?
CodePudding user response:
There are several lengths that you have to take into account:
- The length of the number of items (the first
%d
) - use a length specification there as well to take care of counts with a bigger number of digits that 1 (e.g. if somebody has 23 items of something) - The length of the item name: "Pygmy Puffs" is shorter than "bags of Pygmy Puffs" - before you output the very first line, you have to know the length of the longest item name and add spaces to the end of the line if the current items name is shorter
- The length of the price per item (the second
%d
). Either use a length specification there as well (e.g.M
) but this will create a gap before the price per item, or count the number of digits of the largest item in the list and add spaces at the end of the text (similar to 2.) - The length of the item price for all items. This is the only thing that you already handle right (with
d
). Before that you have to insert the extra spaces from parts 2 and 3 - I would specify a%s
there and then prepare a string with the necessary spaces (e.g. with" ".repeat(spaces)
)
So the final format string would look like this:
"M %s at %d Knuts ea.: %sd%n"
The first parameter is the count, the second the item name, the third the single item price, the fourth a string with spaces to fill up everything and the fifth the price of item times the number of items.
A "cheaper" option would be to have everything specified with a minimum width (as for the first and last parameter in my example) but that will leave blank regions before or after the item, depending on how you specify it.