Advertisement
VelizarAng

MostCommonElement

Mar 24th, 2021
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class MostCommonElement {
  4. public static void GetMostCommonNumber(int[] arr){
  5. int count = Integer.MIN_VALUE;
  6. int tempCount = 0;
  7. int MostCommon = 0;
  8. int temp;
  9.  
  10. for (int i = 0; i < arr.length - 1; i++){
  11. temp = arr[i];
  12. tempCount = 0;
  13.  
  14. for (int j = 1; j < arr.length; j++){
  15. if (temp == arr[j]) {
  16. tempCount++;
  17. }
  18. }
  19.  
  20. if(tempCount > count){
  21. MostCommon = temp;
  22. count = tempCount;
  23. }
  24. }
  25. System.out.println("The most common number: " + MostCommon + " --> " + tempCount + " times");
  26. }
  27.  
  28. public static void main(String[] args) {
  29. Scanner scan = new Scanner(System.in);
  30.  
  31. System.out.print("Enter numbers: ");
  32. String text = scan.nextLine();
  33.  
  34. String[] str = text.split(" ");
  35.  
  36. int[] arr2 = new int[str.length];
  37.  
  38. for (int i = 0; i < arr2.length; i++) {
  39. arr2[i] = Integer.parseInt(str[i]);
  40. }
  41.  
  42. GetMostCommonNumber(arr2);
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement