Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am working in Introduction to Programming using Java. I need a simple and easy

ID: 3571317 • Letter: I

Question

I am working in Introduction to Programming using Java. I need a simple and easy to understand program in Java. Here is the exercise:

(Count occurrence of numbers) 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

Explanation / Answer

import java.util.Scanner;
import java.util.*;
public class HelloWorld{

public static void main(String []args){
/* Hashmap to store number as an integer and its occurence as a value */
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
//integer variable to store input entered by the user
int num;
Scanner input=new Scanner(System.in);
/* prompting user to enetr integers between 1 to 100 */
System.out.print("Enter the integers between 1 and 100: ");
/* run the while loop untill user enters 0 */
while((num=input.nextInt()) != 0){
/* if hashmap does not contain the number */
if(!hm.containsKey(num))
//enter the number with occurence of 1
hm.put(num,1);
/* otherwise just increase the occurence of the number */
else{
int key=hm.get(num);
key++;
hm.put(num,key);
}
  
}
  
  
//for loop to iterate in hash map,hm.get(key) will print value associated to key   
for (int key : hm.keySet()) {
System.out.println(key+" occurs "+hm.get(key)+" times");
}

}
}

/********OUTPUT*********
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
********OUTPUT*********/
/* Note: This code has been tested on eclipse,please do ask in case of any doubt,would glad to help !! */

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote