首页 > 解决方案 > 如何找到二维数组的总数?

问题描述

必须输入学生和科目的数量。(使用随机分数)我想打印学生总分和科目的总分。这是下面给出的代码。

import java.util.*;
class Example{
    public static void readMarks(int[][] x){
        Random r=new Random();
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                x[i][j]=r.nextInt(101);
            }
        }
    }
    public static void printMarks(int[][] x){
        for(int i=0; i<x.length; i++){
            for(int j=0; j<x[i].length; j++){
                System.out.print(x[i][j]+"  ");
            }
            System.out.println();
        }
    }
    public static int[] findStudenTot(int[][] x){
        int tot[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot[i]+=x[i][j];
            }
        }
        return tot;
    }
    public static int[] findSubjectTot(int[][] x){
        int tot1[]=new int[x.length];

        for(int i=0; i<x.length; i++){
            for (int j = 0; j<x[i].length; j++){
                tot1[i]+=x[i][j];
            }
        }
        return tot1;
    }

    public static void main(String args[]){
        Scanner input=new Scanner(System.in);
        System.out.print("Input no of students : ");
        final int N=input.nextInt();

        System.out.print("Input no of subject : ");
        final int S=input.nextInt();

        int[][] marks=new int[N][S];
        readMarks(marks);

        int[] stTotal=findStudenTot(marks);
        int[] subTotal=findSubjectTot(marks);

        System.out.println("total is : "+stTotal);
        System.out.println("total is : "+subTotal);

    }
}

如何打印 stTotal , subTotal?

如果我们假设两个输入都输入 5,那么这个输出总和是:[I@3d4eac69 ...为什么?这些字符是什么以及如何避免这些字符?

标签: java

解决方案


我认为问题在于 findStudentTot 方法,您似乎返回类型为 2D 数组,但返回的是 1D 数组,所以这应该可以解决

public static int[] findStudenTot(int[][] x){
    int tot[]=new int[x.length];

    for(int i=0; i<x.length; i++){
        for (int j = 0; j<x[i].length; j++){
            tot[i]+=x[i][j];
        }
    }
    return tot;
}

推荐阅读