我目前正在尝试获取文本文件,并将文本文件分解为单词。然后我尝试将每个单词存储为二叉树中的节点。这样做后,我也尝试打印二叉树。由于某些原因,当我运行我的代码时,我现在陷入了无限循环,但我不明白在哪里或为什么会这样,如果你能看到我被抓住的地方,这将是一个很大的帮助,谢谢
public class Tester {
public static void main(String[] args) throws FileNotFoundException {
Tester run = new Tester();
run.it();
}
public void it() throws FileNotFoundException {
BTree theTree = new BTree();
String str = this.readInFile();
int position = 0;
String newWord = this.breakIntoWords(str, position);
while(newWord != null){
theTree.add(newWord);
newWord = this.breakIntoWords(str, position);
}
theTree.print();
}
public String readInFile() throws FileNotFoundException {
String myFile = "";
int numWords = 0;
Scanner myScan = new Scanner(new File("Dracula.txt"));
while(myScan.hasNext() == true) {
myFile += myScan.nextLine() + " ";
}
return myFile;
}
public String breakIntoWords(String myFile, int position) {
String nextWord = null;
char next = myFile.charAt(position);
next = Character.toLowerCase(next);
// First trim beginning
while (((next < 'a') || (next > 'z')) && !Character.isDigit(next)) {
position++;
next = myFile.charAt(position);
next = Character.toLowerCase(next);
}
// Now pull only letters or numbers until we hit a space
while(!Character.isWhitespace(next)) {
if (Character.isLetterOrDigit(next)) {
nextWord += myFile.charAt(position);
}
position++;
next = myFile.charAt(position);
}
return nextWord;
}
public class BTree {
private BTNode root;
private int nodeCount;
public boolean add(String word){
BTNode myNode = new BTNode(word);
if(root == null){
root = myNode;
nodeCount++;
return true;
}
if(findNode(word)){
int tmp = myNode.getNumInstance();
tmp++;
myNode.setNumInstance(tmp);
return false;
}
BTNode temp = root;
while(temp != null){
if(word.compareTo(temp.getMyWord()) < 0) {
if(temp.getRightChild() == null){
temp.setLeftChild(myNode);
nodeCount++;
return true;
} else {
temp = temp.getRightChild();
}
} else {
if(temp.getLeftChild() == null){
temp.setLeftChild(myNode);
nodeCount++;
return true;
} else {
temp = temp.getLeftChild();
}
}
}
return false;
}
public boolean findNode(String word) {
return mySearch(root, word);
}
private boolean mySearch(BTNode root, String word) {
if (root == null) {
return false;
}
if ((root.getMyWord().compareTo(word) < 0)) {
return true;
} else {
if (word.compareTo(root.getMyWord()) > 0) {
return mySearch(root.getLeftChild(), word);
} else {
return mySearch(root.getRightChild(), word);
}
}
}
public void print() {
printTree(root);
}
private void printTree(BTNode root) {
if (root == null) {
System.out.print(".");
return;
}
printTree(root.getLeftChild());
System.out.print(root.getMyWord());
printTree(root.getRightChild());
}
public int wordCount() {
return nodeCount;
}
答案 0 :(得分:5)
您使用相同的this.breakIntoWords(str, position)
和str
反复拨打position
,并使用其返回值来决定何时停止。由于从一次迭代到下一次迭代没有任何变化,循环永远不会终止。