在这里,我需要将Set中存在的元素与数组中的元素进行比较。
`System.out.println("Enter Student's Article");
sentence=sc.nextLine();
lowerCase(sentence);
String [] array=sentence.split("[ ,;:.?!]+");
System.out.println("Number of words "+array.length);
Set <String> set=new HashSet<>(Arrays.asList(array));
//System.out.println(set.size());
for(String str:set){
count=0;
for(int j=0;j<array.length;j++){
if(str==array[j])
count++;
System.out.println(count);
}
System.out.println(str+":"+count);
}
}`
代码背后的逻辑是:我收到了一个输入句子并将其转换为小写。然后,我根据代码中提到的某些字符对每个单词进行了拆分,并将每个拆分的单词存储到数组中。现在,我将其转换为集合。现在,我需要对数组中的每个元素计数集合中每个元素的频率。
例如,如果我输入为“ hi hi hi hello”,我将得到字数4 hi:3 hello:1
所以请帮我解决这个问题。
Try the code below and compare the changes with your original code
Scanner sc=new Scanner(System.in);
String sentence=sc.nextLine();
sentence.toLowerCase();
String [] array=sentence.split("[ ,;:.?!]+");
System.out.println("Number of words "+array.length);
Set <String> set=new HashSet<>(Arrays.asList(array));
//System.out.println(set.size());
for(String str:set){
int count=0;
for(int j=0;j<array.length;j++){
if(str.equals(array[j]))
count++;
//System.out.println(count);
}
System.out.println(str+":"+count);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句