gpt4 book ai didi

java - 读取七个整数值并打印出每个值出现的次数的程序

转载 作者:行者123 更新时间:2023-12-04 08:46:03 24 4
gpt4 key购买 nike

正如标题所暗示的那样,我正在尝试输入 7 个整数,并能够输出这些整数以及其中有多少重复项的计数。
使用代码:

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}
for (int i = 0; i < 7; i++) {
int duplicates = 0;
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates + " times.");
}
}
输入:12 23 44 22 23 22 55
我的输出中不断出现重复项,如下所示:
Number 12 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 23 occurs 2 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times.
为了清楚起见,我的目标是:
Number 12 occurs 1 times.
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times
我感谢任何和所有建议。

最佳答案

您可以使用 vector 来存储每个数字的所有出现次数

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] userInput = new int[7];
System.out.print("Enter seven numbers: ");
for (int i = 0; i < 7; i++) {
userInput[i] = input.nextInt();
}

int duplicates[] = new int[7];
for(int i = 0; i < 7; i++)
duplicates[i] = 0;

for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (userInput[i] == userInput[j])
duplicates[i]++;
}
System.out.println("Number " + userInput[i] + " occurs " + duplicates[i] + " times.");
}
}
输入 12 23 44 22 23 22 55 的输出将会:
Number 23 occurs 2 times.
Number 44 occurs 1 times.
Number 22 occurs 2 times.
Number 23 occurs 2 times.
Number 22 occurs 2 times.
Number 55 occurs 1 times.

关于java - 读取七个整数值并打印出每个值出现的次数的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64315084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com