首页 文章

lambda表达式接受来自用户的句子

提问于
浏览
-1

我正在编写一个程序,它使用lambda表达式接受来自用户的字符串a,将其转换为全部小写并删除标点符号,然后按字母顺序列出唯一的单词 . 我无法让我的程序接受用户的句子并删除标点符号 . 我尝试过使用_20204但是我收到错误,所以我一定不能正确使用,或者说这不是正确的代码 . 任何帮助表示赞赏 . 这是我到目前为止的代码:

//I added my own string just to see if the code I have works.
public static void main(String[] args) {
    String[] strings = {"The brown fox chased the white rabbit."};


    System.out.printf("Original strings: %s%n", Arrays.asList(strings));


    Stream<Map.Entry<String, Long>> uniqueWords = Arrays.stream(strings)
         .map(String::toLowerCase)
         //remove punctuation?
         .collect(Collectors.groupingBy(w -> w, Collectors.counting()))
         .entrySet().stream()
         .filter(e -> e.getValue() == 1)
         .distinct();
    System.out.println("Unique words in Alphabetical Order: "+ uniqueWords);
}

1 回答

  • 1

    您可以使用 Scanner 接受用户输入,使用 nextLine() 方法接受来自控制台的一行输入 . 然后你可以toLowerCase()将句子转换为小写,然后split()来创建 Array . 您可以使用正则表达式 \\W+ ,它将拆分为任何非单词字符 .

    你也复杂了 Stream . 您只需使用distinct()sorted()按字母顺序创建唯一值流:

    Scanner in = new Scanner(System.in);
    String[] strings = in.nextLine().toLowerCase().split("\\W+");
    System.out.printf("Original strings: %s%n", Arrays.asList(strings));
    Arrays.stream(strings).distinct().sorted().forEach(System.out::println);
    

    Sample Input/Output:

    This This is. a sentence with duplicate words words, and punctuation!!
    Original strings: [this, this, is, a, sentence, with, duplicate, words, words, and, punctuation]
    a
    and
    duplicate
    is
    punctuation
    sentence
    this
    with
    words
    

相关问题