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

如何修改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 colomnlength instead of columnlength in 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

  1. Fixed the typo: Replaced colomnlength with columnlength in both print loop conditions to resolve the compile error.
  2. Added number spacing: Updated the print statement to include a space after each number, so individual values are easy to distinguish.
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:39:08