我试图在给定的字符串中找到出现次数最多的单词。我的方法是当我直接取字符串数组时正常工作,但是当我取字符串并将其转换为字符串数组时,它不能正常工作。请帮我找出我逻辑中的错误。
我使用 HashMap 来解决这个问题。
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));
}
}
预期输出: hi
它打印 true 时
String arr[] = { "hey","hi","hi","hello","hi" };//hi as input.
但是当输入为字符串并将其拆分为字符串数组时,我没有得到正确的输出。
我执行了您的代码,您的逻辑是正确的,但是使用时出现了一个错误
String str=sc.next();
它只读取字符串中的第一个标记,即 'Hey' 。相反,您应该使用。`
String str=sc.nextLine();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句