如何将Java二维数组以表格形式打印并添加外围索引?
Print Java 2D Array as Indexed Table
Got it, let's solve this problem of printing your 5x5 random integer array with row and column indices in a clean, readable table format. Here's a complete implementation that builds on your existing initialization code:
import java.util.Random; public class Indexed2DArrayPrinter { public static void main(String[] args) { Random rnd = new Random(); int[][] array = new int[5][5]; // Initialize the 2D array with random integers 0-5 for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { array[row][col] = rnd.nextInt(6); } } // Print the table with indices printIndexed2DArray(array); } private static void printIndexed2DArray(int[][] array) { // Get dimensions of the array int rows = array.length; int cols = array[0].length; // Print column indices (top header row) System.out.print(" "); // Empty space for row index header for (int col = 0; col < cols; col++) { System.out.printf("%3d", col); } System.out.println(); // New line after column headers // Print each row with its corresponding row index for (int row = 0; row < rows; row++) { // Print row index with padding System.out.printf("%2d ", row); // Print each element in the row with consistent spacing for (int col = 0; col < cols; col++) { System.out.printf("%3d", array[row][col]); } System.out.println(); // New line after each row } } }
Key Details Explained:
- Consistent Alignment: We use
printfformat strings like%3dfor elements and column indices, plus%2dfor row indices. This ensures every cell takes up the same width, keeping the table neatly aligned even if your values were larger (just adjust the number in the format string if you need more space). - Clear Header Structure: The initial
" "creates empty space in the top-left corner, matching the position of row indices and making the table's layout intuitive. - Reusable Method: The
printIndexed2DArraymethod is separated from the main logic, so you can drop it into other projects to print any rectangular 2D integer array with indices.
Example Output:
0 1 2 3 4 0 5 3 0 2 4 1 1 0 5 3 1 2 2 4 0 5 2 3 3 1 4 0 3 4 0 5 2 1 4
This format makes it easy to quickly reference exactly which row and column any value sits in.
内容的提问来源于stack exchange,提问作者Marck Kopp
相关产品推荐
相关产品推荐

