1

so i'm trying to format my output

System.out.println("Menu:\nItem#\tItem\t\tPrice\tQuantity");
    for(int i=0;i<stock.length;i++){
        System.out.println((i+1)+"\t"+stock[i].Description + "\t\t"+stock[i].price + "\t"+stock[i].quantity);

the output should be like

but it comes out as

2
  • I'd recommend doing some research into printf and String#format Commented Mar 27, 2017 at 1:02
  • 1
    Don't count on tabs to format things correctly. Ever. Just don't use them. Commented Mar 27, 2017 at 1:09

1 Answer 1

5

Java has a nice happy way to print out tables using System.out.format

Here's an example:

Object[][] table = new String[4][];
table[0] = new String[] { "Pie", "2.2", "12" };
table[1] = new String[] { "Cracker", "4", "15" };
table[2] = new String[] { "Pop tarts", "1", "4" };
table[3] = new String[] { "Sun Chips", "5", "2" };

System.out.format("%-15s%-15s%-15s%-15s\n", "Item#", "Item", "Price", "Quantity");
for (int i = 0; i < table.length; i++) {
    Object[] row = table[i];
    System.out.format("%-15d%-15s%-15s%-15s\n", i, row[0], row[1], row[2]);
}

Results:

Item#          Item           Price          Quantity       
0              Pie            2.2            12             
1              Cracker        4              15             
2              Pop tarts      1              4              
3              Sun Chips      5              2              
Sign up to request clarification or add additional context in comments.

3 Comments

System.out.prinf & System.out.format are actually the same thing! As shown in this question.
oh alright i finally did this System.out.printf("Menu:\n%-10s %-10s %12s %14s\n","Item#","Item","Price","Quantity"); for(int i=0;i<stock.length;i++){ System.out.printf("%-10d %-10s %11.2f %8d\n",(i+1),stock[i].Description, stock[i].price, stock[i].quantity);
What if I need table borders as well? Vertical | between columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.