有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java数组:方法不起作用

我似乎在使用三个用户创建的方法以及在主方法中正确调用它们时遇到了问题。据我所知,我没有任何语法错误,因此只剩下逻辑错误,参数看起来也很好

假定程序的输出与下面最后一个输出类似。它是一个接受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) 个答案

  1. # 1 楼答案

    你的方法不是问题所在。这是G.I.G.O(垃圾输入,垃圾输出)的一个例子。您使用不正确的参数调用了方法。在这种情况下,rowsEqTargetSum方法的第三个参数应该是n,而是传递n*(n*n+1)/2(targetSum)。对于任何大于1的n,该值将始终大于n,因此会导致基于代码的索引越界异常

    同样的问题在rowsEqTargetSum(null,0,sum,sum,sum,sum,sum)的尾部调用中的方法中再次出现,这是一个无限递归(您的下一个bug),因为该方法中没有替代(完成)选项。如果您的代码被修复为使用正确的参数调用方法,我相信这将导致下一个堆栈溢出错误

  2. # 2 楼答案

    您需要能够理解什么是异常以及如何解决它。您的代码在其输出中的执行表示为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->int[]rowArr=a[行]

    步骤2->

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

    这导致了java。lang.NullPointerException当您调用returnrowsEqTargetSum时(null,0,sum,sum,sum,sum)