java - Java - 读入 7 个整数,计算重复次数
问题描述
我正在学习 Java 入门课程,但我被困在作业中。目标是使用一维数组编写一个程序,该数组读取 7 个整数,然后显示输入的每个值重复出现的次数(即,如果您输入数字 12 两次,则输出行之一是“数字 12 出现 2 次。 ")
我已经写了一些,但我不知道如何计算每个数组元素出现的次数。我有一个想法,我需要一个方法和第二个数组,但我碰壁了:
public class NumOfOccurrIn7 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Declare scanner and array
Scanner A = new Scanner(System.in);
int counter[] = new int[7];
System.out.print("Please enter 7 numbers: ");
//Populate initial array
for(int t = 0; t < 7; t++) {
counter[t] = A.nextInt();
}
//Process # of reoccurences and print results
for(int t=0; t<7; t++) {
}
for(int t=0; t<7; t++) {
System.out.print("Number " + counter[t] + " occurs " + x +
" times./n");
}
}
public static int CountOccurrance(int counter[]) {
}
}
感谢您的反馈意见!
解决方案
如果数字 12 出现两次,您不希望输出打印两次,因此首先检查该数字是否已被处理。您可以通过遍历数组元素before t
来做到这一点,如果其中一个与当前数字相同,则不会打印任何内容。
接下来检查数组的其余部分并计算当前数字出现的次数,然后打印消息。
// Process # of reoccurences and print results
for (int i = 0; i < 7; i++) {
boolean print = true;
int count = 0;
for (int j = 0; j < 7; j++) {
if (counter[j] == counter[i]) {
if (j < i) {
print = false;
break;
}
count++;
}
}
if (print) {
System.out.println("Number " + counter[i] +
" occurs " + count + " times.");
}
}
推荐阅读
- python - 从 rasa 模型的输出中删除意图排名
- c - 从 txt 文件中读取数字矩阵
- python - 重复整个 tkinter 程序
- python - 无法对齐可滚动标签中的文本
- mariadb - MyISAM 表删除后 MariaDB Galera Closter 崩溃
- d3.js - 如何使用 highcharts/d3.js 或任何其他图表库绘制线加条形图?
- multithreading - 为什么 PostThreadMessage() 给我一个未列出的错误消息 ERROR_MESSAGE_SYNC_ONLY?
- sql - SQL Server - aggregate the data
- powershell - Invoke-Command 更改输出编码
- dynamics-crm - 动态 365 从电子邮件中的字段更改默认值