I am having a trouble printing the last line and I do not how it will be printed. can someone help me to solve this problem? i have a source code atleast and you can refer it to output of source code and possible output.
Source code:
import java.util.*;
class Main{
public static int getfrequentelement (int[]a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}
public static void main (String[] args)
{
Scanner x = new Scanner(System.in);
System.out.print("Enter the number of frequent flyers: ");
int size1 = x.nextInt();
int[] a = new int[size1];
System.out.print("Enter the frequent flyers: ");
for(int i=0; i<a.length; i++)
{
a[i] = x.nextInt();
}
System.out.println("Most frequent = "+getfrequentelement(a));
}
}
Output of source code:
Enter the number of frequent flyers: 6
Enter the frequent flyers: 7 7 7 9 9 9
Most frequent = 9
Expected Output:
Enter the number of frequent flyers: 6
Enter the frequent flyers: 7 7 7 9 9 9
None
Thank you, i hope you can solve it
>Solution :
You must make your method getfrequentelement(int[]a) static, because you cannot call a non-static method in a static method.
public static int getfrequentelement (int[]a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}