gpt4 book ai didi

java - 计算不同的单词

转载 作者:行者123 更新时间:2023-12-02 01:04:55 25 4
gpt4 key购买 nike

如何计算跨多行文本中的不同单词?

Input data: You will read the text of the email from the keyboard. It can span multiple lines and contains only lowercase letters of the English alphabet and spaces.

Output data: A single integer representing the number of distinct words in the email will be displayed.

我有这个代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String args[] ) throws Exception {
Set<String> words = new TreeSet<>();
int count = 0;
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
String line;
while((line = reader.readLine()) != null){
words.add(line);
count++;
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println(count);
}

基本上它只适用于测试,但在其余部分是的,它是错误的,因为我知道这是因为它仍然读取一个空白空间,我可以修复什么?

最佳答案

改变

words.add(line);

添加每行中的单词。在空白处拆分,然后添加生成的标记。就像,

words.addAll(Arrays.asList(line.split("\\s+")));

然后改变

System.out.println(count);

System.out.println(words.size());

最后,消除 count (您不需要它,并且 Set 按集合中元素的数量“计数”元素;即 words.size())。并且,除非出于某种原因需要对元素进行排序,否则请使用 HashSet

Set<String> words = new TreeSet<>();

应该是(据我所知)

Set<String> words = new HashSet<>();

关于java - 计算不同的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60188442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com