猿问

排序列表的分配

我的第16章作业是这样的。

创建一个应用程序

  • 接受用户输入的字符串或单词

  • 按字母顺序打印每个单词

  • 打印输入的元素总数

到目前为止我有这个

import java.util.Arrays;

import java.util.Collection;

import java.util.Collections;

import java.util.List;

import java.util.Scanner;




public class Chapter16Assignment {

        public static void main(String[] args){


            Scanner input = new Scanner(System.in);



            String userInput = "";

            System.out.print(" Enter a line of words: ");

            userInput = input.nextLine();

            List<String> userString = Arrays.asList(userInput);

            String[]userInput

            //userString.add(userInput);

            //.split

            Collections.sort(userString);

            System.out.println(userString);

            //System.out.println("Frequency of words: " + Collection.frequency(userString));


            }




    }

我需要使用 split 或其他东西。我想我可以在第 3 部分中使用排序方法和频率。


我希望输出输入一行单词,然后按字母顺序打印这些单词,然后打印单词数量。目前它还没有做任何事情。但它正在获取用户的输入。


胡说叔叔
浏览 91回答 1
1回答

长风秋雁

这就是如何使用 split 方法将字符串转换为字符串数组。我没有使用列表,因为我想向您展示一种稍微不同的方法来解决此问题。我正在删除空格并将所有内容转换为小写。如果你想做的话,这取决于你。Scanner input = new Scanner(System.in);String userInput;System.out.print("Enter a line of words: ");userInput = input.nextLine().replace(" ", "").toLowerCase();String[] userInputSplit = userInput.split(""); // Splits arrayArrays.sort(userInputSplit); // Sorts arraySystem.out.println(Arrays.toString(userInputSplit)); // Prints sorted array// Checks for frequency of each letter using mapsMap<String, Integer> countMap = Arrays.stream(userInputSplit)&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Function.identity(), v -> 1, Integer::sum));// Prints mapSystem.out.println("Frequency of words: " + countMap.toString());输出:Enter a line of words: The quick brown fox jumps over the lazy dog[a, b, c, d, e, e, e, f, g, h, h, i, j, k, l, m, n, o, o, o, o, p, q, r, r, s, t, t, u, u, v, w, x, y, z]Frequency of words: {a=1, b=1, c=1, d=1, e=3, f=1, g=1, h=2, i=1, j=1, k=1, l=1, m=1, n=1, o=4, p=1, q=1, r=2, s=1, t=2, u=2, v=1, w=1, x=1, y=1, z=1}编辑:就像@AndyTurner建议的那样,您也可以使用Collectors.counting()这使得语法更容易理解,但它将返回 Long 而不是 IntegerMap<String, Long> countMap = Arrays.stream(userInputSplit)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));Collectors.counting本质上是Map<String, Integer> countMap = Arrays.stream(userInputSplit)&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));使用 HashSet 和 Collections.Frequency:HashSet<String> uniqueValues = new HashSet<String>(userInputList);for (String value : uniqueValues) {&nbsp; &nbsp; System.out.println("Frequency of " + value + " is: " + Collections.frequency(userInputList, value));}
随时随地看视频慕课网APP

相关分类

Java
我要回答