You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java幻方程序求助:完善checkArrays方法实现幻方有效性验证

解决幻方验证的checkArrays方法实现问题

先帮你修正现有代码里的一个小错误:getRowSums方法的循环条件写错了,把r < magicS[r].length改成c < magicS[r].length,不然循环逻辑会出错,无法正确计算行和。

接下来就是实现checkArrays方法的核心逻辑:我们需要先确定一个基准和(比如取第一行的和),然后逐一验证所有行、列、对角线的和是否都等于这个基准和,只要有一个不相等就返回false,全部一致则返回true。

下面是完整的修正后代码,重点看checkArrays的实现:

import java.util.Scanner;

public class PerfectSquare {

    static Scanner sc; 
    static int[][] magicS; 

    /**
     * Builds perfect square
     */
    public static void buildSquare() {
        magicS = new int[3][3];
        for (int r = 0; r < 3; r++) {
            for (int c = 0; c < 3; c++) {
                //asks the user to input a number.
                System.out.println("Please type number for row " + (r + 1) + " and column " + (c + 1));
                magicS[r][c] = sc.nextInt();
            }
        }
    }

    /**
     * Prints perfect square
     */
    public static void printSquare() {
        for (int r = 0; r < 3; r += 1) {
            for (int c = 0; c < 3; c += 1) {
                System.out.print(magicS[r][c] + " ");
            }
            System.out.println("");
        }
    }

    /**
     * Adds each row together
     *
     * @param r
     * @return
     */
    public static int getRowSums(int r) {
        int sum = 0;
        // 修正循环条件:把r改成c
        for (int c = 0; c < magicS[r].length; c++) {
            sum += magicS[r][c];
        }
        return sum;
    }

    /**
     * Adds each column together
     *
     * @param c
     * @return
     */
    public static int getColSums(int c) {
        int sum = 0;
        for (int r = 0; r < magicS.length; r++) {
            sum += magicS[r][c];
        }
        return sum;
    }

    /**
     * Adds each diagonal together
     *
     * @return
     */
    public static int[] getDiaganolSums() {
        int[] sums = new int[2];
        for (int d = 0; d < magicS.length; d++) {
            sums[0] += magicS[d][d];
            sums[1] += magicS[d][magicS.length - 1 - d];
        }
        return sums;
    }

    /**
     * Checks to see if the sum of each row, column, and diagonal should all be
     * the same, If perfect returns true.
     *
     * @return
     */
    public static boolean checkValid() {
        int[] rowSums = new int[magicS.length];
        for (int r = 0; r < magicS.length; r++) {
            rowSums[r] = getRowSums(r);
        }
        int[] colsSums = new int[magicS.length];
        for (int c = 0; c < magicS.length; c++) {
            colsSums[c] = getColSums(c);
        }
        int[] diagSums = getDiaganolSums();
        boolean perfect = checkArrays(rowSums, colsSums, diagSums);
        // 添加结果提示,让用户直观看到验证结果
        if (perfect) {
            System.out.println("This is a valid magic square!");
        } else {
            System.out.println("This is NOT a valid magic square.");
        }
        return perfect;
    }

    /**
     * checks if each row, column, and diagonal are equal to each other
     *
     * @param rowSums
     * @param colSums
     * @param diagSums
     * @return
     */
    public static boolean checkArrays(int[] rowSums, int[] colSums, int[] diagSums) {
        // 先判断输入数组是否有效,避免空指针或长度异常
        if (rowSums == null || colSums == null || diagSums == null || rowSums.length == 0) {
            return false;
        }

        // 取第一行的和作为基准和
        int targetSum = rowSums[0];

        // 检查所有行的和是否等于基准和
        for (int sum : rowSums) {
            if (sum != targetSum) {
                return false;
            }
        }

        // 检查所有列的和是否等于基准和
        for (int sum : colSums) {
            if (sum != targetSum) {
                return false;
            }
        }

        // 检查两条对角线的和是否等于基准和
        for (int sum : diagSums) {
            if (sum != targetSum) {
                return false;
            }
        }

        // 所有和都一致,返回true
        return true;
    }

    /**
     * The main method asks the user to input numbers that correlate to a row
     * and column When run, a 3 x 3 array of the numbers inputted will be printed.
     *
     * @param args
     */
    public static void main(String[] args) {
        //allows to get info from user
        sc = new Scanner(System.in);
        //executes the buildSquare method
        buildSquare();
        //executes the printSquare method
        printSquare();
        //executes the checkValid method
        checkValid();
        // 关闭Scanner避免资源泄漏
        sc.close();
    }
}

代码说明:

  1. 修正getRowSums循环条件:原代码的循环条件错误,导致无法正确计算行和,现在已经修复。
  2. checkArrays方法逻辑:
    • 先做参数有效性检查,避免空指针或空数组的异常情况。
    • 以第一行的和作为目标基准和,只要其他所有行、列、对角线的和都等于这个值,就是有效幻方。
    • 逐一遍历行和、列和、对角线和,只要发现不匹配的就立即返回false,提升验证效率。
  3. 额外优化:在checkValid方法里添加了结果提示,让用户能直观看到验证结果;main方法里添加了sc.close()避免资源泄漏。

内容的提问来源于stack exchange,提问作者John Gordon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:52:28