java - 如何在 Java EE 中找到数组中重复元素的出现次数?
问题描述
我尝试编写一个代码片段来查找Java中一维数组中重复元素的出现次数......计数器似乎没有超过1......有人可以帮助我......这是我的代码:
import java.util.*;
public class duplicate{
public static void main(String args[]){
int i,n,c,j,m=-1;
Scanner a = new Scanner(System.in);
System.out.println("Enter the value of length");
n=a.nextInt();
int b[] = new int[n];
System.out.println("Enter the elements of the array.");
for(i=0;i<n;++i)
b[i]=a.nextInt();
for(i=0;i<n;++i){
c=0;
if(b[i]==m)
continue;
else{
m=b[i];
for(j=0;j<=i;++j){
if(b[j]==b[i])
c++;
}
System.out.println("The element"+b[i]+" has occured "+c+" times.");
}
}
}
}
解决方案
您的代码片段有很多粗略的东西。首先,我建议您正确格式化您的代码,并可能改进一些变量命名。
我拿了你的部分代码来证明它是错误的:
for (i = 0; i < n; ++i) {
c = 0;
if (b[i] == m) {
continue;
} else {
/*
* here you always set m to the current value of the array so in the next
* iteration, your check in the "if clause" will be true what means that the
* counter will never count up if there are 2 or more consecutive equal numbers
*/
m = b[i];
for (j = 0; j <= i; ++j) {
// also this logic is flawed, because you only count the values
// before the current one
if (b[j] == b[i])
c++;
}
System.out.println("The element" + b[i] + " has occured " + c + " times.");
}
}
我宁愿建议您用于此类任务的方法是使用 aHashMap
并计算那里每个值的出现次数。
例子:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of length");
int size = scanner.nextInt();
int[] values = new int[size];
System.out.println("Enter the elements of the array.");
for (int i = 0; i < size; i++) {
values[i] = scanner.nextInt();
}
Map<Integer, Integer> map = new HashMap<>();
for (int key : values) {
if (map.containsKey(key)) {
int occurrence = map.get(key);
occurrence++;
map.put(key, occurrence);
} else {
map.put(key, 1);
}
}
for (Integer key : map.keySet()) {
int occurrence = map.get(key);
System.out.println(key + " occurs " + occurrence + " time(s).");
}
}
推荐阅读
- python - 家得宝购买历史下载
- java - 如何在 TextView 中显示 HTML 文本?
- scala - 证明 runtimeClass 满足 Scala 中的 Bound 类型
- docker - Dockerfile:COPY 不起作用(即使他可以找到该文件)
- javascript - 如何开始在 Formio.js 中构建自定义组件?文档在哪里?
- visual-studio - PHP CS Fixer 不会在 Visual Studio Code 中加载 .php-cs 文件
- android - “未解决的参考:数据绑定”
- ruby-on-rails - 如何在 rake 任务中使用 postgres 复制功能?
- wagtail - Wagtail:过滤 PageChooserPanel 中的可用页面
- mongodb - MongoDB使用另一个字段的值添加新字段