求适配现有Array_two类的二维数组打印方法实现
Solution for Implementing printMatrix Static Method
Got it, let's build that printMatrix static method for your Array_two class. The goal is to print the 10×10 matrix in a clean, readable format—especially since your values go from 1 to 100, we'll want to align the numbers so the matrix looks neat.
Complete Implementation
Here's how to write the method, plus the full context of your Array_two class (including your existing populate method and a test main method to verify everything works):
public class Array_two { private int[][] values; // Constructor to initialize the 10x10 array public Array_two() { this.values = new int[10][10]; } // Your existing populate method public void populate() { int num = 1; for (int i = 0; i < 10; ++i) { for (int j = 0; j < 10; ++j) { this.values[i][j] = num; ++num; } } } // The static printMatrix method we're adding public static void printMatrix(int[][] grid) { // Optional but useful: check for invalid input to avoid errors if (grid == null || grid.length == 0) { System.out.println("Invalid matrix to print."); return; } // Loop through each row in the matrix for (int[] row : grid) { // Loop through each element in the current row for (int num : row) { // Format each number to 3 characters wide to align 1-100 neatly System.out.printf("%3d ", num); } // Move to the next line after finishing a row System.out.println(); } } // Test method to run the code public static void main(String[] args) { Array_two matrix = new Array_two(); matrix.populate(); printMatrix(matrix.values); } }
Key Details Explained
- Static Method Structure: Declared as
public staticso it can be called without an instance ofArray_two, and it accepts anint[][]parameter as required. - Input Validation: The quick check for null/empty grids prevents unexpected runtime errors, making the method more robust.
- Formatted Output: Using
System.out.printf("%3d ", num)ensures every number takes up 3 characters of space. This aligns single-digit (1-9), double-digit (10-99), and triple-digit (100) numbers perfectly, keeping the matrix organized. - Row Breaks: After printing all elements in a row,
System.out.println()starts a new line for the next row, maintaining the matrix structure.
Sample Output
When you run the main method, you'll get a clean 10×10 matrix snippet like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ... 91 92 93 94 95 96 97 98 99 100
内容的提问来源于stack exchange,提问作者user9701731
相关产品推荐
相关产品推荐

