对于Magic Square Java程序,这是一个逻辑错误吗?

时间:2013-06-10 21:39:31

标签: java arrays loops magic-square

我编写了一个创建nxn矩阵的程序,然后检查矩阵是否是魔术方块。在我的方法magicCheck中,所有元素总计(sum)然后除以n(行数或列数)以生成magicNumber。此magicNumber用于分别比较每行,每列和对角线的总和,以查看它们是否匹配。程序运行正常,但是当我输入应该是魔方的数字时,程序说它不是。我的代码顺序是否有错误,或者我在数学中遗漏了什么?

import java.util.*;

public class MagicSquare 
{
static int row, col, n, rows, columns, listSize;
static Scanner console = new Scanner (System.in);

public static void createArithmeticSeq(int [] list)
{   
    int first; 
    int diff;
    //prompt user for first and diff to create list
    System.out.println("Choose the first number and diff to create" + 
    " an arithmetic sequence.");
    System.out.println("Enter first and diff : ");
    first = console.nextInt();
    diff  = console.nextInt();
    //process to create list of n*n elements 
    for (int i=0; i<listSize; i++)
    {
        list[i]=first+i*diff;
    }
}

public static void matricize (int [] list, int [][] matrix)
{
System.out.println("Matricize arithmetic sequence:");
    int i = 0;
//loop through each row
    for (row=0; row<matrix.length; row++)
    {
    //loop through each column
        for (col=0; col<matrix[row].length; col++)
        {
        //populate matrix with values from list
        matrix[row][col] = list[i++];
        }
     }
}
public static void printMatrix(int [][] matrix)
{

    for (row=0; row < matrix.length; row++)
    {
        for (col=0; col < matrix[row].length; col++)
            System.out.printf("%2d" + " ", matrix[row][col]);

        System.out.println("\n");
    }
}

public static void reverseDiagonal(int [] [] matrix)
{ 
System.out.println("Reverse the diagonals:");
    int temp;
    for (row=0; row<matrix.length / 2; row++)
    {
        temp = matrix[row][row];
        matrix[row][row] = 
            matrix[matrix.length - 1 - row] [matrix.length - 1 - row];
        matrix[matrix.length - 1 - row][matrix.length - 1 - row] = temp;
    }
    for (row=0; row<matrix.length / 2; row++)
    {
        temp = matrix[row][matrix.length - 1 - row];
        matrix[row][matrix.length - 1 - row] = 
            matrix[matrix.length - 1 - row][row];
        matrix[matrix.length - 1 - row][row] = temp;
    }
}

public static void magicCheck(int [] list, int [] [] matrix)
{
System.out.println("Is the matrix a magic square?");
    int sum=0, sumRow=0, sumCol=0, sumDiag1=0, sumDiag2=0, magicNumber=0;
    for(int i=0; i<listSize; i++)
    {
        sum = sum + list[i];    
        magicNumber = (sum/n);

    for(row=0; row<matrix.length; row++)
    {
            //sum each row, then compare to magicNumber
        for(col=0; col<matrix[row].length; col++)
        sumRow = sumRow + matrix[row][col];
        while (sumRow == magicNumber)
        {
            for(col=0; col<matrix.length; col++)
            {
                for(row=0; row<matrix[col].length; row++)
                {
                sumCol = sumCol + matrix[row][col];
                    while (sumCol == magicNumber)
                    {
                    for (int row=0; row<matrix.length; row++)
                        {
                        sumDiag1 += matrix[row][row];
                        }
                        while (sumDiag1 == magicNumber)
                        {
                        for (int row=n-1; row>=0; row--)
                        sumDiag2 += matrix[row][row];
                            while(sumDiag2 == magicNumber)
                            System.out.println("It is a magic square.");
                            System.out.println("The magic number is " + magicNumber + ".");
                        }
                    }
                }
            }
        }
    }
    }
            System.out.println("It is not a magic square.");

}
public static void main (String [] args)
{
    //prompt user for array size
    System.out.println("Enter size of array (in form nxn), n:");
    n = console.nextInt();
    rows = n;
    columns = n;
    listSize= (n*n);    
    int [] list = new int [listSize];
    createArithmeticSeq (list);
    int [] [] matrix = new int [rows] [columns];
    matricize(list, matrix);
    printMatrix(matrix);
    System.out.print("\n");
    reverseDiagonal(matrix);
    printMatrix(matrix);
    magicCheck(list, matrix);   
}

}

1 个答案:

答案 0 :(得分:1)

这不是一个真正的答案(评论有点长),但我建议你这样做:

// returns 'null' if not a magic square, otherwise returns the magic number
public static Integer getMagicNumber(int[] list, int[][] matrix)
{
  ...
  for (int i = 0; i < listSize; i++)
  {
    ...
  }
  for (row = 0; row < matrix.length; row++)
  {
    //sum each row, then compare to magicNumber
    for(col = 0; col < matrix[row].length; col++)
      sumRow = sumRow + matrix[row][col];
    if (sumRow != magicNumber)
      return null;
  }
  for (col = 0; col < matrix.length; col++)
  {
    //sum each column, then compare to magicNumber
    ...
  }
  ...
  return magicNumber;
}

然后在main中执行:

Integer magicNumber = getMagic(...);
if (magicNumber == null)
  System.out.println("It is not a magic square.");
else
{
  System.out.println("It is a magic square.");
  System.out.println("The magic number is " + magicNumber + ".");
}

我确信有人会Integer取值null时出现问题,但这只是一种做事方式。

我不想为你重写所有代码,我相信你可以从中找到它。

它使嵌套块保持最小,这使得代码更易读,更容易出错。