【问题标题】:Magic Square program Java with array带数组的魔方程序Java
【发布时间】:2018-11-14 14:00:13
【问题描述】:

我想编写一个 Magic Square,其中数组的利用率已经到位,但是当我想运行它时,它显示 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at MagicSquare.main(MagicSquare.java:6) 我应该怎么办?它会显示

4   9   2        7 1 6
3   5   7  not   3 5 7
8   1   6        4 9 2 



public static void main(String[] args) { 
    Scanner input = new Scanner (System.in);

    int n = Integer.parseInt(args[3]);
    if (n % 2 == 0) throw new RuntimeException("n must be odd");

    int[][] magic = new int[n][n];

    int row = n-1;
    int col = n/2;
    magic[row][col] = 1;


    for (int i = 2; i <= n*n; i++) {
        if (magic[(row + 1) % n][(col + 1) % n] == 0) {
            row = (row + 1) % n;
            col = (col + 1) % n;
        }
        else {
            row = (row - 1 + n) % n;

        }
        magic[row][col] = i;
    }


    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (magic[i][j] < 10)  System.out.print(" ");  
            if (magic[i][j] < 100) System.out.print(" ");  
            System.out.print(magic[i][j] + " ");
        }
        System.out.println();
    }

}

我还应该从这个程序中添加或删除什么?

【问题讨论】:

  • 你用至少 4 个参数运行你的程序吗?数组是从零开始的!
  • wdym 参数?
  • 你是如何开始你的程序的...例如java MyClass ...,您的具有 args[3] 的行预计在类名之后至少有 4 件事。
  • 只公开一个

标签: java


【解决方案1】:

根据你的程序,运行时需要提供4个参数。例如:如果类名是 Test

java Test 1 1 1 3

结果:

  4   9   2
  3   5   7
  8   1   6

【讨论】:

  • 你怎样才能让它像 8 1 6 和 4 9 2 交换位置
  • 我运行了你的程序,在控制台中传递了 4 个参数。上面给出了结果。更新了我的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多