我的第 16 章作业是这样的。
Create an application which
- accepts user input of a string or words
- prints each word back in alphabetical order
- prints the total number of elements typed
到目前为止我已经有了
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 部分中使用排序方法和频率。
我希望输出输入一行单词,然后按字母顺序打印这些单词,然后打印单词数量。目前它还没有做任何事情。它获取用户的输入。
最佳答案
这就是如何使用 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 array
Arrays.sort(userInputSplit); // Sorts array
System.out.println(Arrays.toString(userInputSplit)); // Prints sorted array
// Checks for frequency of each letter using maps
Map<String, Integer> countMap = Arrays.stream(userInputSplit)
.collect(Collectors.toMap(Function.identity(), v -> 1, Integer::sum));
// Prints map
System.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 而不是 Integer
Map<String, Long> countMap = Arrays.stream(userInputSplit)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Collectors.counting 本质上是
Map<String, Integer> countMap = Arrays.stream(userInputSplit)
.collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));
使用 HashSet 和 Collections.Frequency:
HashSet<String> uniqueValues = new HashSet<String>(userInputList);
for (String value : uniqueValues) {
System.out.println("Frequency of " + value + " is: " + Collections.frequency(userInputList, value));
}
关于java - 排序列表的分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58312927/