Java:方法不起作用

时间:2016-11-30 23:27:08

标签: java arrays loops if-statement methods

我似乎遇到了三个用户创建的方法的问题,并在main方法中正确调用它们。我没有任何我知道的语法错误,所以留下逻辑错误,参数看起来也很好。

程序假设输出类似于下面的最后一个输出。这是一个采用2D数组并检查它是否为magic square的程序。每种方法都有责任审核/检查过程,以确定它是否是一个魔方。

我真的很感激帮助这项工作,我很难过。

代码:

import java.util.Arrays;

public class Magic10
{
    // A method to check whether rows equal the target sum
    private static boolean rowsEqTargetSum(int[][] a, int targetSum, int n, int row, int col, int sum)
    {
    // Calculate the sum of each row ... if magic, then equal to targetSum      
        for(row=0; row<n; row++)
        {
            System.out.print("row "+row+": ");
            for(col=0; col<n; col++)
            {
                int value = a[row][col];
                sum += value;
                if (col > 0)
                    System.out.print(" + "); // print plus before all except 1st
                System.out.print(value);
            }
            System.out.println(" = "+sum);
            if(sum != targetSum)
            {
                System.out.println("Row sum incorrect : Not a magic Square!");
            }
        }
        return rowsEqTargetSum(null, 0, sum, sum, sum, sum);
    }
    // A method to check whether diagonals equal the target sum 
    private static boolean diagonalEqTargetSum(int[][] a, int targetSum, int n, int row, int col, int sum)
    {
        System.out.print("diagonal: ");
        for(int pos=0; pos<n; pos++)
        {

            row = n-1 - pos;
            col = pos;
            int value = a[row][col];
            sum += value;
            if (pos > 0)
                System.out.print(" + "); // print plus before all except 1st
            System.out.print(value);
        }
        System.out.println(" = "+sum);
        if(sum != targetSum)
        {
            System.out.println("Diagonal is incorrect : Not a magic Square!");
        }
        return diagonalEqTargetSum(null, 0, 0, sum, sum, sum);
    }
    // A method to check whether all numbers are used exactly once in the 2D array
    private static boolean allNumbersRepresented(int[][] a, int n, int col, int row)
    {
    // Lastly, we check that every number from 1 to n is represented
        final int nSquare=n*n;
        boolean[] flag= new boolean[n*n];

        for(row=0; row<n; row++)
        {
            for(col=0; col<n; col++)
            {
                int num = a[row][col];
                if (n < 1 || num > nSquare)
                {
                    System.out.println("Number out of range : Not a magic Square!");
                }
                if (flag[num-1]) 
                {
                    System.out.println("Duplicate number : Not a magic Square!");
                }
                flag[num-1] = true;
            }
        }
        return allNumbersRepresented(null, 0, 0, 0);
    }

    public static void main(String []args)
    {
        int[][] a ={{4,9,2},
                    {3,5,7},
                    {8,1,6}};
        final int n=a.length;
        final int targetSum=n*(n*n+1)/2;

        System.out.println(" The following two dimensional array is Magic!");   
        for (int i = 0;i< a.length;i++)
        {
            System.out.println(Arrays.toString(a[i]));
        }

        // Calls rowsEqTargetSum Method
        if (!rowsEqTargetSum(a, targetSum, targetSum, targetSum, targetSum, targetSum))
        {
            return;
        }
        // Calls diagonalEqTargetSum Method
        if (!diagonalEqTargetSum(a, targetSum, targetSum, targetSum, targetSum, targetSum))
        {
                 return;
        }
        // Calls allNumbersRepresented Method
        if (!allNumbersRepresented(a, targetSum, targetSum, targetSum))
        {
                return;
        }
    }
}

当前输出(调用方法有什么问题?)

 The following two dimensional array is Magic!
[4, 9, 2]
[3, 5, 7]
[8, 1, 6]
row 0: 4 + 9 + 2Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    at Magic10.rowsEqTargetSum(Magic10.java:14)
    at Magic10.main(Magic10.java:91)

输出看起来有点像这样:

row 0: 4 + 9 + 2 = 15
row 1: 3 + 5 + 7 = 15
row 2: 8 + 1 + 6 = 15
diagonal: 8 + 5 + 2 = 15
 The following two dimensional array is Magic !
[4, 9, 2]
[3, 5, 7]
[8, 1, 6]

2 个答案:

答案 0 :(得分:0)

你的方法不是问题。这是G.I.G.O(Garbage in,Garbage out)的案例。您使用不正确的参数调用了您的方法。在这种情况下,rowsEqTargetSum方法的第三个参数应为n,而是传递n *(n * n + 1)/ 2(targetSum)。对于任何大于1的n,此值将始终高于n,因此会根据您的代码导致索引超出范围异常。

同样的问题在你的tailEqTargetSum(null,0,sum,sum,sum,sum)的尾调用中再次发生,这是一个无限递归(你的下一个bug)因为没有替代(完成)选项方法。我相信如果你的代码被修复以调用具有适当参数的方法,那么将导致你的堆栈溢出的下一个错误。

答案 1 :(得分:0)

您需要能够了解异常是什么以及如何解决它。您在其输出中执行的代码表示java.lang.ArrayIndexOutOfBoundsException以及您获取它的行。

纠正逻辑的第一步是避免java.lang.ArrayIndexOutOfBoundsException

您可以控制迭代,如下所示

for(row=0; row<a.length; row++)
    {
        int[] rowArr = a[row];
        System.out.print("row "+row+": ");
        for(col=0; col<rowArr.length; col++)
        {
            int value = a[row][col];
            sum += value;
            if (col > 0)
                System.out.print(" + "); // print plus before all except 1st
            System.out.print(value);
        }
        System.out.println(" = "+sum);
        if(sum != targetSum)
        {
            System.out.println("Row sum incorrect : Not a magic Square!");
        }
    }

步骤1 - &gt; int [] rowArr = a [row];

步骤2-&gt;

int[] rowArr = a[row];
System.out.print("row "+row+": ");
for(col=0; col<rowArr.length; col++)

当你调用return rowsEqTargetSum(null,0,sum,sum,sum,sum)时,这会导致java.lang.NullPointerException;