Write a program that reads the integers between 1 and 100 and counts the occurre
ID: 3691637 • Letter: W
Question
Write a program that reads the integers between 1 and 100 and counts the occurrences of each. Assume the input ends with 0. Here is a sample run of the program:
Enter the integers between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
This is my current code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[100];
System.out.print("Enter the integars between 1 and 100: ");
for (int i = 0; i < 100; i++) {
int n = input.nextInt();
numbers[n] += n;
if (n == 0) {
break;
}
}
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] != 0) {
if (numbers[i] / i > 1) {
System.out.println(i + " occurs " + numbers[i] / i + " times ");
}
} else {
System.out.println(i + " occurs " + numbers[i] / i + " time ");
}
}
}
}
Explanation / Answer
import java.util.Scanner;
/**
* @author
*
*/
public class CountOccurrences {
/**
* @param args
*/
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
int[] numbers = new int[100];
int[] count = new int[101];
// prompt to enter 1 to 100 nums
System.out.print("Enter the integars between 1 and 100: ");
for (int i = 0; i < 100; i++) {
int n = input.nextInt();
numbers[i] = n;
if (n == 0) {
break;
}
}
// counting occurances
for (int i = 1; i < count.length; i++) {
int n = numbers[i - 1];
if (n != 0) {
count[n]++;
}
}
// printing the occurances count
for (int i = 1; i < count.length; i++) {
if (count[i] != 0) {
System.out.println(i + " occurs " + count[i] + " times ");
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
input.close();
}
}
}
OUTPUT:
Enter the integars between 1 and 100: 2 5 6 5 4 3 23 43 2 0
2 occurs 2 times
3 occurs 1 times
4 occurs 1 times
5 occurs 2 times
6 occurs 1 times
23 occurs 1 times
43 occurs 1 times
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.