Home > Enterprise >  Trouble wrong printing of frequency in array loops JAVA
Trouble wrong printing of frequency in array loops JAVA

Time:11-07

I am having a difficulty printing the last line which it is wrong, it should print the input on how many repeated number of my choice. (Please look for the OUTPUT and POSSIBLE OUTPUT) sorry my English is bad.

Source Code:

import java.util.*; 

class Main{ 
  
public static void main (String[] args) { 
    
  Scanner x = new Scanner(System.in);
      System.out.print("Enter n: ");
      int size1 = x.nextInt();
      int[] a = new int[size1];
      System.out.println("Enter elements:");
      
      
      for(int i=0; i<a.length; i  ) {
        a[i] = x.nextInt();
      }
    
    Arrays.sort(a); 
    int n=a.length;
    
    int countofmax = 1;
    int temp = a[0]; 
    int count = 1; 
    
    for (int i = 1; i < a.length; i  ) 
    { 
      if (a[i] == a[i - 1]) 
        count  ; 
      else
      { 
        if (count > countofmax) 
        { 
          countofmax = count; 
          temp = a[i - 1]; 
        } 
        count = 1; 
      } 
    } 
  
   
    if (count > countofmax) 
    { 
     
      countofmax = count; 
      temp = a[n - 1]; 
    } 

    countofmax=temp;
    System.out.print("Enter y: ");
    countofmax= x.nextInt();

    

  System.out.println("FREQUENCY: " temp); 
  } 
} 

Output of Mine: (As you can see here the frequency is wrong since I input three times of 9)

        Enter n: 4
        Enter elements:
        9
        9
        9
        8
        Enter y: 9
        FREQUENCY: 9

EXPECTED OUTPUT SHOULD FLASH:

        Enter n: 4
        Enter elements:
        9
        9
        9
        8
        Enter y: 9
        FREQUENCY: 3

CodePudding user response:

What you seem to be doing is finding the maximum frequency and the element. Not that of finding the frequency of your choice y.
So, first get your y, then find it's frequency.

int y = x.nextInt();
int count=0;
Arrays.sort(a);
for (int i = 0; i < a.length; i  ) 
{ 
    if (a[i] == y)
    {
        count  ;
        for(int j=i 1;j<a.length;j  )
        {
            if(a[j]==y)
                count  ;
            else
                break;
        }
        break;
    }
 }
System.out.println("Frequency of "  y  " is "  count);
  •  Tags:  
  • java
  • Related