首页 > 解决方案 > 如何在二维数组中显示唯一编号并对唯一编号求和

问题描述

import java.io.*;
public class Arrayact {
    public static void main(String[] args) throws IOException {
        BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
        int row, maxRow, col, maxCol;
        int yctr = 0;
        int sum = 0;
        int y;
        System.out.print("Number of row/s: ");
        maxRow = Integer.parseInt(cin.readLine());
        System.out.print("Number of colmun/s: ");
        maxCol = Integer.parseInt(cin.readLine());
        int arr[][] = new int[maxRow][maxCol];
        System.out.println();

        for (row = 0; row < maxRow; row++) {
            for (col = 0; col < maxCol; col++) {
                System.out.print("Index[" + row + "][" + col + "]: ");
                arr[row][col] = Integer.parseInt(cin.readLine());
            }
        }

        System.out.println();
        for (row = 0; row < maxRow; row++) {
            for (col = 0; col < maxCol; col++) {
                y = arr[row][col];
                if (arr[row][col] == y) {
                    yctr++;
                    sum += arr[row][col];
                }
            }
        }
        System.out.println("ther are " + yctr + "unique element and their sum is " + sum);
    }
}

这是我的代码,我想显示唯一编号和唯一编号的总和,但我只是得到输入的数量和输入的总和。有人知道这里有什么问题吗?

标签: javaarrays

解决方案


您可以将计算唯一元素总和的部分重构为使用 a Set,这是一种可以保存唯一元素的数据结构。因此,对于每个,y您可以检查它是否存在于集合中,如果不存在,则将其添加到总和中并将此数字添加到集合中,这样它就不会再次添加到总和中。

        Set<Integer> numbers = new HashSet<>();

        for (row = 0; row < maxRow; row++) {
            for (col = 0; col < maxCol; col++) {
                y = arr[row][col];
                if (!numbers.contains(y)) {
                    numbers.add(y);
                    sum += y;
                }
            }
        }
        System.out.println("ther are " + numbers.size() + "unique element and their sum is " + sum);

推荐阅读