How to print a table of arrays?

后端 未结 3 1484
北荒
北荒 2021-01-26 01:44

I\'m here to see if anyone would be able to help out with the problem.

I\'m trying to print a table out which would look something like this

                    


        
3条回答
  •  滥情空心
    2021-01-26 02:24

    Assuming all people have the same number of months:

    System.out.println("\n\nSummer Internship Salary Information:");
    for (int j=0; j < table[0].length; j++) {
        System.out.print("\tMonth #" + (j+1));
    }
    for (int i=0; i < table.length; i++) {
        System.out.print("\nPerson #" + (i+1));
        for (int j=0; j < table[i].length; j++) {
            System.out.print("\t$" + table[i][j]);
        }
    }
    System.out.println();
    

    Notice that the Person# is taken out of the inner loop, and the column headings are printed first.

    Also beware that if any number is too wide (wider than a tabstop) it will break the layout. You would have to be cleverer to fix that (find maximum width for each column first or truncate the values)

    (Edited to put tabs and newlines in better places; fewer strings and no trailing tabs)

提交回复
热议问题