Reputation: 3
I am trying to find the most occurrence word in a given string. My approach is to work correctly when I directly take an array of string but when I take String and convert it to the array of string than it does not work properly. Please help me to find out the error in my logic.
I used HashMap for this problem.
import java.util.*;
public class FindingmostOccurrencewordsinGivenString {
static String OccurreneceofWords(String [] arr)
{
HashMap<String,Integer> hs=new HashMap<String,Integer>();
for(int i=0;i<arr.length;i++)
{
if(hs.containsKey(arr[i]))
hs.put(arr[i], hs.get(arr[i])+1);
else
hs.put(arr[i], 1);
}
Set<Map.Entry<String, Integer>>set=hs.entrySet();
Integer value=0;
String key="";
for(Map.Entry<String, Integer>m:set)
{
if(m.getValue() > value)
{
value=m.getValue();
key=m.getKey();
}
}
return key;
}
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
String str1[]=str.split("\\s+");
String arr[] = { "hey","hi","hi","hello","hi" };//hi
System.out.println(OccurreneceofWords(str1));
}
}
Expected output: hi
It prints true when
String arr[] = { "hey","hi","hi","hello","hi" };//hi as input.
But when input as String and split it into the array of string that time I do not get the correct output which is hi.
Upvotes: 0
Views: 62
Reputation: 71
I executed your code your logic is correct but there is a single error use using
String str=sc.next();
Which only reads the first token in the string i.e., 'Hey' .Instead you should use.`
String str=sc.nextLine();
Upvotes: 1