如何修改Java代码实现指定列长的数字方阵按行打印?
Fixing Your Java Matrix Printing Issue
Let's walk through the problems in your code and fix them to get the properly formatted N×N matrix you want.
First, the key issues in your original code
- Variable name typo: You wrote
colomnlengthinstead ofcolumnlengthin both of your print loops. That's a compile error waiting to happen—Java can't recognize the misspelled variable name. - No formatting for readability: Right now, you're printing every number back-to-back with
System.out.print(), so all numbers run together in one long line. We need spacing between numbers and line breaks after each row to see the matrix structure.
Modified Working Code
package MagicMatrix; import java.util.Scanner; public class Matrix { Scanner scanner = new Scanner(System.in); public static void main(String[] args) { new Matrix(); } public Matrix() { System.out.println("Give column length of matrix\n"); int var00 = 1; int columnlength = scanner.nextInt(); int[][] matrix = new int[columnlength][columnlength]; // Populating the matrix was already correct! for (int i = 0; i < columnlength; i++) { for (int j = 0; j < columnlength; j++) { matrix[i][j] = var00; var00++; } } // Fixed print loop with proper formatting for (int i = 0; i < columnlength; i++) { for (int j = 0; j < columnlength; j++) { // Add space between numbers to avoid clumping System.out.print(matrix[i][j] + " "); } // Move to a new line after finishing each row System.out.println(); } } }
What we changed
- Fixed the typo: Replaced
colomnlengthwithcolumnlengthin both print loop conditions to resolve the compile error. - Added number spacing: Updated the print statement to include a space after each number, so individual values are easy to distinguish.
- Added row line breaks: After printing all numbers in a row (the inner loop), we call
System.out.println()to start the next row on a new line.
Bonus: Clean Alignment for Larger Matrices
If you want numbers to line up neatly even with larger matrices (e.g., 5×5 where values go up to 25), use formatted printing instead:
System.out.printf("%3d ", matrix[i][j]);
The %3d tells Java to reserve 3 character widths for each integer, keeping the matrix perfectly aligned regardless of number size.
内容的提问来源于stack exchange,提问作者Twannemannn
相关产品推荐
相关产品推荐

