我是编程新手,对这个问题感到困惑,我尝试了几种不同的方法,但均未成功。
实现(源代码)一个程序(命名为LargestOccurenceCount),该程序从用户读取正非零整数值,找到最大值,并对其进行计数。假定输入以数字0结尾(作为停止循环的前哨值)。程序应忽略任何负输入,并应继续读取用户输入,直到输入0。程序应显示最大值和出现次数
Scanner reader = new Scanner(System.in);
int num = 0;
int array[] = null;
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
array[num] = num;
}
示例1:
输入正整数(0退出):3 4 5 -9 4 2 5 1 -5 2 5 0
最大值:5 发生3次
程序应输出输入的最大值和在输入0之前输入的次数。
答案 0 :(得分:0)
将问题分为两部分。 1.找到最大值
int findLargest(int[] array) {
assert array.length > 0;
int result = array[0];
for (int element : array) {
if (element > result) {
result = element;
}
}
return result;
}
int countOccurences(int[] array, int value) {
int occurences = 0;
for (int element : array) {
if (element == value) {
occurences++;
}
}
return occurences;
}
请注意,数组应至少包含一个元素;
答案 1 :(得分:0)
如果没有要求仅使用数组,则可以使用ArrayList
来存储用户输入
List<Integer> list = new ArrayList<>();
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
list.add(num);
}
然后,如果您擅长使用流API,则有一个非常简洁的解决方案:
Map.Entry<Integer, Long> lastEntry = list.stream()
.collect(groupingBy(Function.identity(), TreeMap::new, counting()))
.lastEntry();
System.out.println(
"Largest value: " + lastEntry.getKey() +
" Occurrences: " + lastEntry.getValue() + " times");
答案 2 :(得分:0)
您可以使用以下代码段:
// part of reading the values from command line and
// putting them into this array is omitted
int[] array = ...;
int biggest = 0;
int occurance = 0;
for(int num : array) {
if(num > biggest) {
biggest = num;
occurance = 0;
}
if(num == biggest) {
occurance++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);
如评论中所述,我已经省略了您从命令行读取值的部分,因为这似乎不是您的问题。
另一种直接读取数据的方法,不需要数组和一个循环中的所有内容:
Scanner scanner = new Scanner(System.in);
int biggest = 0;
int occurance = 0;
int num;
while (true) {
System.out.print("Enter a number: ");
// this may throw an Exception if the users input is not a number
num = Integer.parseInt(scanner.nextLine());
if(num == 0) {
// user entered a 0, so we exit the loop
break;
}
if(num > biggest) {
biggest = num;
occurance = 1;
} else if(num == biggest) {
biggest++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);