我想创建一个用作单词计数器的程序。我打算使用树结构来存储单词。我还想计算单词的频率。我已经构建了二叉树和获取用户输入的方法。我该怎么做?请帮忙。
这是我的代码。
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 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);
}