Code a Java console application that reads in seven integer values entered on a
ID: 3147749 • Letter: C
Question
Code a Java console application that reads in seven integer values entered on a single line, and prints out the number of occurrences of each value. Using Java single dimension arrays, the application counts the number of occurrences of each of the seven values. The application then the prints out the number of occurrences of each of the seven values to the screen.
*********************************************************************************************************************************************************************************************************************
As an example:
Enter 7 numbers: 12 23 44 22 23 22 55
Number 12 was entered 1 time.
Number 23 was entered 2 times.
Number 44 was entered 1 time.
Number 22 was entered 2 times.
Number 55 was entered 1 time.
*********************************************************************************************************************************************************************************************************************
import java.util.Scanner;
//public class
public class CountOccurence
{
//main class
public static void main(String args[])
{
int i, j, count = 0;
//array declration
int arr[]=new int[7];
//scanner object creation
Scanner in = new Scanner(System.in);
System.out.printf("Enter 7 numbers: ");
//loop for 7 times
for(i=0; i< 7; i++)
{
arr[i] = in.nextInt();
}
//nested loop to find the count
for(i=0; i<7; i++)
{
for(j=i; j<7; j++)
{
if(arr[i] == arr[j])
{
count++;
}
}
//display count for each digit
System.out.printf("Number %d was entered %d times. ",arr[i], count);
//set count to zero after each iteration
count = 0;
}
}
}
}
Only issue so far is that this code prints out all numbers entered. I need this program to print the numbersout but if it has duplicate numbers they only need to be printed out once.
This updated program does not print out the final number.
Explanation / Answer
problem1
Updated program doesn't print out the final number because in the loop condition, you have put i < 7 and j < 7.
it should be i <= 7 and j <=7.
problem2
Change the following loop condition, and start from 1, and inside put an additional condition, if (j<i), then break the loop and does not print the number.
for(j=1; j<=7; j++)
{
if(arr[i] == arr[j] & j < i)
{
break;
}
if(arr[i] == arr[j])
{
count++;
}
}