In: Computer Science
JAVA Write a program that reads the integers between -100 and 100 and counts the occurrences of each with ascending order.
input: line1:number of figures
line2:number
Sample Input
5 -3 100 -1 -2 -1
Sample Output
-3 1 -2 1 -1 2 100 1
Here I am sending code, screens of code and outputs. If you have any questions or queries comment below. Thank you.
Java code:
import java.util.*;
public class Occurence {
public static void main(String args[])
{
Scanner sc = new
Scanner(System.in);
int size = sc.nextInt(); // reading
size from user
List<Integer> arr = new
ArrayList(); // initializing arraylist
for(int i=0 ; i<size ; i++) //
loop for adding elements to arraylist
{
arr.add(sc.nextInt()); // reading and adding elements to
arraylist
}
/*treeset arrange the elements in
increasing order without repetition*/
TreeSet<Integer> ts = new
TreeSet<Integer>(arr); // initializing treeset
Iterator<Integer> it =
ts.iterator(); // creating iterator
while(it.hasNext()) // loop for
printing element and occurrence
{
int n =
it.next();
System.out.println(n+" "+Collections.frequency(arr,n)); //printing
element and occurrence
}
}
}
output: