Reputation: 189
I'm new to java. I am trying to figure out how to format multiple arrays that are being filled in while the program is running (thanks to user input).
When I print the arrays, they do not format. I would use " " spaces, but the output of the arrays are dependent on what the user inputs. What I have is:
System.out.println("Order Summary:");
System.out.println();
System.out.println("Type Size Quantity Price");
System.out.println("---------------------------------------------------------");
for (i = 0; i < boolCount; i++)
{
System.out.println(typeArray[i] + sizeArray[i] + quantityArray[i] + priceArray[i]); //How to format?
}
which would print out whatever is in the arrays without spaces. typeArray, sizeArray, and priceArray are String arrays, while quantityArray is an integer array.
I probably need to do System.out.printf(Enter code here) but I'm not sure how to do that with arrays. Any help would be appreciated.
EDIT: This is what I get if I add "\t" between the arrays:
System.out.println(typeArray[i] + "\t\t" + sizeArray[i] + "\t" + quantityArray[i] + "\t" + priceArray[i]);
Order Summary:
Type Size Quantity Price
---------------------------------------------------------
BBQ Chicken Large 2 $25.98
Chicken-Bacon Ranch Personal 22 $175.78
Meat Lovers Extra Large 33 $791.67
Order total: $993.43
---------------------------------------------------
EDIT: This is what I get with:
System.out.printf("%-23.23s %-14.14s %-12.12d %-5.5s", typeArray[i], sizeArray[i], quantityArray[i], priceArray[i]);
Order Summary:
Type Size Quantity Price
---------------------------------------------------------
Exception in thread "main" java.util.IllegalFormatPrecisionException: 12
at java.util.Formatter$FormatSpecifier.checkInteger(Formatter.java:2984)
at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2729)
at java.util.Formatter.parse(Formatter.java:2560)
at java.util.Formatter.format(Formatter.java:2501)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at pizzamenu.PizzaMenu.main(PizzaMenu.java:372)
Java Result: 1
Upvotes: 2
Views: 1078
Reputation: 1375
You can use format specifiers.
Format specifiers follow the following format:
%[flags][width][.precision][argsize]typechar
So in your case, you would do the following:
System.out.printf("%-23s %-14s %-12d %-5s", typeArray[i], sizeArray[i], quantityArray[i], priceArray[i]);
More info on format specifiers: https://sharkysoft.com/archive/printf/docs/javadocs/lava/clib/stdio/doc-files/specification.htm
Upvotes: 1