【问题标题】:Magic Square generator魔方发生器
【发布时间】:2015-12-03 01:23:47
【问题描述】:

我正在尝试开发一个程序来创建和打印一个 n X n “魔方”,其中 n 是用户生成的奇数整数。但是,我不断收到相同的错误“java.lang.ArrayIndexOutOfBoundsException:3”

算法总结:

  1. 将 1 放在第一行(第 0 行)的中心

  2. 按照以下规则放置2,3,4...n

向上和向右移动到新位置 (row,col) 即 row = row-1, col = col+1 如果 row = -1 (行不在数组中),则将数字放在 (n-1, col) 中的最后/底部行中

如果 col = n(列不在数组中),则将数字放入 (row, 0)

从上角方块移动时,将下一个数字放在左下角方块中,如果位置已被占用,则将新数字放在前一个数字的下方

import java.util.*;
public class MagicSquare
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);

System.out.println("Enter an odd integer:");

int n = input.nextInt();

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

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

 for(int i=2; i <=n*n; i++)
{
   if(magic[row-1][col+1]==0){
     row=row-1;
     col=col+1;
   }
   else{
     row=row+1;
   }
   if(row==-1)
     row = n-1;
   if (col== n)
     col=0;
   magic[row][col]=i;
}
for(int x = 0; x<n; x++)
{
  for(int y=0; y<n; y++)
    System.out.print("|"+magic[x][y] +"|\t");
  System.out.println();
 }
}
}

编辑 - 格式化

【问题讨论】:

  • 你能重新格式化规则吗?我在解析它们时遇到了问题——尤其是最后的那部分。

标签: java arrays algorithm


【解决方案1】:

所以,请遵守您的规则(感谢您重新格式化它们!):

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

    System.out.println("Enter an odd integer:");

    int n = input.nextInt();

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

    // Place 1 in the center of the first row ( row 0)
    int row = 0;
    int col = (n-1)/2;
    magic[row][col] = 1;

    for(int i=2; i <=n*n; i++)
    {
       // Move up and right to a new position
       col = col + 1;
       row = row - 1;
       // row is off the array
       if (row == -1)
           row = n - 1;
       // col is off the array
       if (col == n)
           col = 0;
       // if the place is taken, place the new number under the previous number
       if( magic[row][col] !=0 )
       {
         row = row + 1;
         if (row == n)
           row = 0;
       }

       magic[row][col]=i;
    }

    for(int x = 0; x < n; x++)
    {
      for(int y=0; y < n; y++)
        System.out.print("|"+magic[x][y] +"|\t");
      System.out.println();
    }
}

这与更改条件 (!= 0) 以检测占用的位置非常相似,并且通过分离所有加法和减法,当多个发生在行。

我还没有测试过这段代码,所以它可能仍然有问题,但希望这会让你走上正确的道路!

【讨论】:

    【解决方案2】:

    在您的for 循环中,您将row 重置为结束:

    if(row==-1)
      row = n-1;
    

    但是在下一次迭代中,您使用row + 1 进行索引:

    if(magic[row+1][col+1]==0)
    

    这将是过去的结束。

    【讨论】:

    • 谢谢,这肯定是问题的一部分。我相信我已经纠正了它,我已将更新的循环放在上面的问题中。但是,我仍然遇到错误“java.lang.ArrayIndexOutOfBoundsException:-1”。有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多