In: Computer Science
Write a Java program that reads a list of integers into an array. The program should read this array from the file “input.txt”. You may assume that there are fewer than 50 entries in the array. Your program determines how many entries there are. The output is a two-column list. The first column is the list of the distinct array elements; the second column is the number of occurrences of each element. The list should be sorted on entries in the first column, largest to smallest. Sample output (for input.txt: -12 3 -12 4 1 1 -12 1 -1 1 2 3 4 2 3 -12): Number. Count 4 2 3 3 2 2 1 4 -1 1 -12 4
code:
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args)throws IOException {
Scanner scanner = new Scanner(new File("input.txt"));
int [] arr = new int [50];//since there are less than 50 entries in the array
int k = 0;
while(scanner.hasNextInt()){
arr[k++] = scanner.nextInt();
}
//sorting the array using bubble sort algorithm in descending order
for (int i = 0; i < ( k - 1 ); i++) {
for (int j = 0; j < k - i - 1; j++) {
if (arr[j] < arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
int temp,count;
System.out.println("Numbers\tCount");
int i = 0;
while(i<k){
count = 1;//keep count of particular element
int current = arr[i];
while(arr[i] == arr[i+1]){
++count;//updating the count of a particular element
i++;
if(i == k)
break;//end of the array reached so break the loop
}
System.out.println(current+"\t"+count);//displaying the value
++i;
}
}
}
output:
code screenshot: