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

Java二维数组问题:如何将n×n数组主对角线设为1其余为0?

Fixing Your Java Matrix to Show 1s on the Main Diagonal

Hey there! The issue here is that when you create an int[][] array in Java, all elements are automatically initialized to 0—which is why you're seeing all zeros right now. To get 1s on the main diagonal (where the row index equals the column index), you just need to add a quick check when setting up your array.

Here's the modified code:

import java.util.Scanner;

class Test1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[][] num = new int[n][n];
        
        // Add this loop to set main diagonal elements to 1
        for (int i = 0; i < n; i++) {
            num[i][i] = 1; // Row index == column index means main diagonal
        }
        
        // Print the matrix as before
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(num[i][j] + " ");
            }
            System.out.println();
        }
        scan.close(); // Don't forget to close the scanner!
    }
}

What Changed?

  • Added a loop that iterates through each row index i, and sets num[i][i] to 1—this targets exactly the main diagonal positions (since for the main diagonal, row number = column number).
  • Also added scan.close() to properly clean up the Scanner resource, which is a good practice.

When you run this, for n=3 you'll get:

1 0 0 
0 1 0 
0 0 1 

内容的提问来源于stack exchange,提问作者Hellmud

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:43:58