นับจำนวนตัวเลขซ้ำครั้งมากที่สุด
โจทย์
Write a program that takes a series of integers as input, identifies the highest number, and counts how many times it appears. The input should conclude with the number 0.
| Input | Output |
|---|---|
| 3 5 2 5 5 5 0 | Largest number: 5 Occurrences: 4 |
| 0 | Largest number: No numbers entered Occurrences: 0 |
โค้ด
import java.util.*;
public class Program {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int biggest = Integer.MIN_VALUE;
int occurrence = 0;
while (true) {
int input = scanner.nextInt();
if (input == 0) break;
if (input > biggest) {
biggest = input;
occurrence = 1;
} else if (input == biggest) {
occurrence++;
}
}
System.out.println("Largest number: " + (biggest == Integer.MIN_VALUE ? "No numbers entered" : biggest));
System.out.println("Occurrences: " + occurrence);
}
}คำอธิบาย
ปรับปรุงล่าสุด