You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Java二维数组以表格形式打印并添加外围索引?

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 printf format strings like %3d for elements and column indices, plus %2d for 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 printIndexed2DArray method 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:21:36