In: Computer Science
Write a program in Java that reads in a set of positive integers and outputs how many times a particular number appears in the list. You may assume that the data set has at most 100 numbers and -999 marks the end of the input data. The numbers must be output in increasing order. For example, for the data 15 40 28 62 95 15 28 13 62 65 48 95 65 62 65 95 95 -999
The output is
Number Count
13 1
15 2
28 2
40 1
48 1
62 3
65 3
95 4
import java.util.Scanner; public class NumberCounts { public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] arr = new int[100]; int count = 0; for (int i = 0; i < arr.length; i++) { arr[i] = in.nextInt(); if (arr[i] == -999) break; count++; } int temp; for (int i = 0; i < count; ++i) { for (int j = 0; j < count - 1; ++j) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } System.out.println("Number\tCount"); for (int i = 0; i < count; i++) { int prevCount = 0, nextCount = 0; for (int j = 0; j < count; j++) { if (arr[j] == arr[i]) { if (j < i) { prevCount++; } else if (j > i) { nextCount++; } } } if (prevCount == 0) { System.out.println(arr[i] + "\t\t" + (nextCount + 1)); } } } }