我想创建一个用作单词计数器的程序。我打算使用树结构来存储商店字。我也想计算单词的频率。我已经构建了二叉树和方法来获取用户输入。我该怎么办?请帮助。
这是我的代码。
public class Node {
int a;
String b;
Node leftChild;
Node rightChild;
Node(String b){
this.a = 0;
this.b = b;
this.leftChild = null;
this.rightChild = null;
}
public void display(){
System.out.println(" "+ b + " ");
}
public class Tree {
public Node root;
public Tree(){
root = null;
}
public void insert(String word){
Node newNode = new Node(word);
newNode.b = word;
if(root==null){
root = newNode;
}else{
Node current = root;
Node parent;
while(true){
parent = current;
if(word.compareToIgnoreCase(current.b)<0){
current = current.leftChild;
if(current == null){
parent.leftChild = newNode;
return;
}
}else{
current = current.rightChild;
if(current == null){
parent.rightChild = newNode;
return;
}
}
}
}
public Node search(String word){
Node current = root;
while(!current.b.equalsIgnoreCase(word)){
if(word.compareToIgnoreCase(current.b)<0){
current= current.leftChild;
}else{
current = current.rightChild;
}
if (current == null)
return null;
}
return current;
}
public void inOrder(Node localRoot){
if(localRoot != null){
inOrder(localRoot.leftChild);
localRoot.display();
inOrder(localRoot.rightChild);
}
}
这是主要方法。 (虽然它甚至还没有完成)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Tree newTree = new Tree();
Scanner inputString = new Scanner(System.in);
System.out.println("Type the paragraph and press \"Enter\" :");
String input = inputString.nextLine();
newTree.inOrder(newTree.root);
}
答案 0 :(得分:1)
使用地图或类似的东西来存储单词的出现次数会更容易。
但是如果你想出于某些原因使用树形结构并且我理解你的问题,你应该修改你的插入方法:
//...
}else{
current = current.rightChild;
if(current == null){
parent.rightChild = newNode;
return;
} /*begin modification*/ else if (current.b.equalsIgnoreCase(word)) { // check if word already is stored in tree
++current.a; // increase counter
} /*end modification*/
}
现在你可以使用你的插入方法并计算单词添加相同的时间。但请注意,由于Node构造函数中的this.a = 0;
,您的计数器此时从0开始。
在main方法中,您可以将段落拆分为单词(String[] words = input.split(" ");
),并在for循环中使用newTree.insert(words[i]);
添加数组中的每个单词。
如果这不是您想知道的,则必须更清楚地指出您的问题。
答案 1 :(得分:0)
恕我直言,你树的问题在于存在 - 你不需要一个!
计算单词频率有一个规范的,非常简洁的解决方案:
public static Map<String, Integer> wordCounts(String input) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (String word : input.toLowerCase().split("(?s)\\s+"))
map.put(word, map.containsKey(word) ? map.get(word) + 1 : 1);
return map;
}