java
8.1: Frequency
Design and implement an application that reads an arbitrary number
of integers that are in the range 0 to 50 inclusive and counts how
many occurrences of each are entered. After all input has been
processed, print all of the values (with the number of occurrences)
that were entered one or more times. The output should be one
frequency count per line with the following format:
3 occurrences of 2
7 occurrences of 5
SPECIFICATION OF NAMES: Please name your application class Frequency
Here is the Java code. If you have any queries then please ask me in the comment section. Upvote if you like the answer.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Frequency
{
int returnCount(int n, int []list,int len)
{
int count=0,i=0;
while(i<len)
{
if(n==list[i])
count++;
i++;
}
return count;
}
public static void main(String []args) throws IOException
{
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
Frequency obj = new Frequency();
int i,j,count;
int num[] = new int[1000];
String[] strNums;
System.out.println("Enter integers between 0 to 50 separated by spaces : ");
strNums = bi.readLine().split("\\s");
for(i=0; i<strNums.length; i++)
{
num[i] = Integer.parseInt(strNums[i]);
}
for(i=0; i<strNums.length; i++)
{
if(num[i]<0 || num[i]>50)
{
System.out.println("\nEnter the numbers between 0 and 50(both inclusive) only");
return;
}
}
for(i=0;i<strNums.length;i++)
{
for(j=0;j<i;j++)
if(num[i]==num[j])
break;
if(i==j)
{
count = obj.returnCount(num[i],num,strNums.length);
if(count>0)
{
System.out.printf("%d occurs %d times\n",num[i],count);
}
}
}
}
}
Get Answers For Free
Most questions answered within 1 hours.