排序和消除重复项

Sort and eliminating duplicates

Input data You will read from the keyboard the text of the email that needs to be converted. It can be spread over several lines.

Output data: The distinct words in the text read, in alphabetical order, will be displayed one at a time.

Restrictions and specifications The text does not contain more than 100 words, and each word can contain up to 20 characters. To shorten the execution time of your program use BufferedReader The class that contains the main method must be called prog

import java.util.*;
 public class Main {
public static void main(String args[] ) throws Exception {
    Scanner in = new Scanner(System.in);
    Set<String> set = new TreeSet<>();
    int size = in.nextInt();
    for(int i=0 ;i < size ;i++){
        set.add(in.next());
    }
    Iterator i = set.iterator();
    while(i.hasNext()) {
        System.out.println(i.next());
    } 
   }
 }

我只需要说一次,我该怎么做呢?那是我的密码! 我使用 size 变量从键盘输入数字,然后在论坛中输入文本,但我想直接阅读文本,我可以这样做吗

要使用 while 从输入中读取,您可以这样做:

Scanner in = new Scanner(System.in);
Set<String> set = new TreeSet<>();

while(!in.hasNext("exit")){ //you can put any word for exit
    set.add(in.next());
}

for(String e : set){
    System.out.println(e);
}

这是最简单的方法。

更新(BufferedReader)

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

try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){

    String line;
    while((line = reader.readLine()) != null && !line.equals("exit")){

        words.addAll( //add elements from List<String> into Set
                Arrays.asList( //change array with words into List<String>
                    line.split("\s+") //split line by space -> String[] (array with words)
                )
        );

    }

}catch(Exception e){
    e.printStackTrace();
}

for(String word : words){
    System.out.println(word);
}

TreeSet 将自动删除重复项并按字母顺序排序。