I have created a 2D array and want to print the output. I want to label the columns and rows. I have labeled the rows. but I can not figure out how to label the columns. Something link this:
A B C D E F
Row 1 * * * * * *
Row 2 * * * * * * Row 3 * * * * * * Row 4 * * * * * * Row 5 * * * * * * Row 6 * * * * * * Row 7 * * * * * * Row 8 * * * * * * Row 9 * * * * * * Row 10 * * * * * * Row 11 * * * * * * Row 12 * * * * * * Row 13 * * * * * *Like I said I have the rows and the *, but how do I get the A b c labels on the columns.
for(int i = 1; i < 13; i++)
{
System.out.print("Row " + i + " " );
for(int 开发者_如何学编程j = 0; j < 6; j++)
{
System.out.print(seats[i][j] + " ");
}
System.out.println(); //for spacing
}
assuming you know how many columns you have and it's less than 26, you could add this on to the start of your code...
for (int j = 0; j < seats[0].length; j++)
System.out.print(((char) ('A' + j)) + "\t");
System.out.println();
going past 26 is a little more complex, let me know if you need that.
You probably need to do two things - create labels and format the output. To create the labels I would do something like
char a = 'A';
for(int j = 0; j < 6; j++) {
char label = a+j;
System.out.print(label);
System.out.print(" ");
}
System.out.println();
but this will give a messy output.
I would personally create an HTML table to do the formatting - working it out yourself is tedious.
Simply add something like
System.out.println(" A B C D E F");
before the loop shown in the question.
I'm assumming each element of the array is a single character wide, adapt accordingly if that were not the case. Also, the leading spaces are to account for the "Row ##" header shown on each subsequent line.
Also [unrelated to the question], rather than using hard-coded values for the limits of the loop (here 6 and 13), use the arrays' length attribute instead, i.e.
for(int i = 1; i < seats.length; i++)
{
System.out.print("Row " + i + " " );
for(int j = 0; j < seats[i].length; j++)
{
System.out.print(seats[i][j] + " ");
}
System.out.println(); //for spacing
}
精彩评论