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

Java矩阵编程问题求助:代码错误排查与需求实现指导

代码中的问题及修正方案

1. 错误读取N的值

N = bi.read(); 读取的是输入字符的ASCII码值,比如输入3时,实际得到的是字符'3'的ASCII码51,而非整数3。
修正:改用readLine()读取整行后转为整数:

N = Integer.parseInt(bi.readLine());

2. 输出了无关字符串

题目要求读写过程中不得输出任意无关字符串,但代码中存在System.out.println("Enter the elements of the matrix")、System.out.println("The elements of the matrix")、System.out.print("SUM of DIAGONAL elements of the matrix = "+sum)这些多余输出,必须全部删除。

3. 矩阵读取逻辑混乱

当前的for循环逻辑错误,无法正确将输入的N行数据填充到二维数组中。
修正:直接循环N次,每次读取一行数据并填充到矩阵的对应行:

for (int row = 0; row < N; row++) {
    stringar();
    for (int col = 0; col < N; col++) {
        mat[row][col] = a1[col];
    }
}

4. 未读取X和Y的值

题目要求最后一行输入X和Y,但代码完全没有处理这部分输入,导致无法获取目标元素A[X][Y]。
修正:在读取完矩阵后,读取最后一行并解析X和Y:

stringar();
int X = a1[0];
int Y = a1[1];

5. 缺少单数字和的计算逻辑

题目要求计算A[X][Y]的单数字和,但代码中没有实现该功能。单数字和的计算可以通过循环求和,或者利用数学公式简化:

  • 若数字为0,单数字和为0;
  • 否则,若数字模9等于0且数字不为0,单数字和为9;
  • 否则为数字模9的结果。
    实现代码:
public static int getSingleDigitSum(int num) {
    if (num == 0) return 0;
    int res = num % 9;
    return res == 0 ? 9 : res;
}

6. 未计算最终结果Q

代码仅计算了主对角线元素和,但没有完成除以单数字和得到Q的步骤,也没有输出Q。
修正:获取单数字和后计算Q并输出:

int targetNum = mat[X][Y];
int singleSum = getSingleDigitSum(targetNum);
int Q = sum / singleSum;
System.out.println(Q);

修正后的完整代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Matrix {
    static BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
    static String[] a;
    static int[] a1;
    
    public static void stringar() throws IOException {
        a = bi.readLine().split(" ");
        a1 = new int[a.length];
        for (int i1 = 0; i1 < a.length; i1++) {
            a1[i1] = Integer.parseInt(a[i1]);
        }
    }

    public static int getSingleDigitSum(int num) {
        if (num == 0) return 0;
        int res = num % 9;
        return res == 0 ? 9 : res;
    }

    public static void main(String args[]) throws Exception {
        int N = Integer.parseInt(bi.readLine());
        int[][] mat = new int[N][N];

        // 读取矩阵
        for (int row = 0; row < N; row++) {
            stringar();
            for (int col = 0; col < N; col++) {
                mat[row][col] = a1[col];
            }
        }

        // 读取X和Y
        stringar();
        int X = a1[0];
        int Y = a1[1];

        // 计算主对角线和
        int sum = 0;
        for (int i = 0; i < N; i++) {
            sum += mat[i][i];
        }

        // 计算单数字和
        int targetNum = mat[X][Y];
        int singleSum = getSingleDigitSum(targetNum);

        // 计算并输出Q
        int Q = sum / singleSum;
        System.out.println(Q);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:36:16