给定N个数字显示M * M格式

时间:2018-04-27 20:33:04

标签: java algorithm

我们给第一行的数字(n) 程序输出:下一行包含空格分隔的整数,描述第一种排列。

n=m^2
例如:9

Output:1  2  3
       4  5  6
       7  8  9

例如:16

输出:
asa

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n;
        int m;
        System.out.println("Enter number of team");
        n = scanner.nextInt();

        m = (int) Math.sqrt(n);

        int[][] array = new int[m][m];


        for(int i=0;i<m;i++) {
            for(int j=0;j<m;j++) {
                array[i][j]=j+1;
                System.out.print(array[i][j]);
            }
            System.out.println();
        }

    }

}
  

购买我的节目输出

     

参赛作品:3

     

输出:

     

123

     

123

     

123

1 个答案:

答案 0 :(得分:0)

你仍然没有问任何问题,但我认为你的程序给出了错误的答案(因为它确实如此)并且你不知道为什么。 例如:对于n = 16,它打印:

1234
1234
1234
1234

以下代码片段负责:

array[i][j]=j+1;
System.out.print(array[i][j]);

首先,您不打印空格,因此数字不会分开。其次,您必须使用另一个公式:i*m+j+1(因为数字取决于ij)。此外,保持数组没有意义,但这不是错误。

建议更正:

System.out.print(m*i+j+1 + " ");