java - 如何在二维数组中显示唯一编号并对唯一编号求和
问题描述
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);
}
}
这是我的代码,我想显示唯一编号和唯一编号的总和,但我只是得到输入的数量和输入的总和。有人知道这里有什么问题吗?
解决方案
您可以将计算唯一元素总和的部分重构为使用 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);
推荐阅读
- c# - asp.net core 2.1中的自定义长时间运行任务调度程序
- sql - sp_executesql 未使用“with”子句运行 sql
- c++ - 如何使用 C++ 的选择性打开特性?
- python-3.x - 如何将滚动条移动到文本小部件内部
- c++ - 使用 ReadProcessMemory() 将未知大小的字符数组或字符串读入 wstring
- webpack - Webpack 字符串替换 Ionic 3 / Cordova 5 Config.xml
- android - 标签栏和导航抽屉对齐
- python - 将列表复制到矩阵python3时出错
- javascript - 挖掘对象以满足条件并返回高于级别的属性
- vba - 从单元格中按名称搜索并打开 Word 文件