我正在创建一个程序,它从一个文件中获取输入(在我的例子中,是学生姓名和他们的相关编号),并以带迭代器的预排序形式、带递归的post+inoorder形式打印出来。在我的驱动程序中,我已经成功地创建和添加了学生的名字+关联的数字+用预排序迭代器打印出来。然而,我的问题是,当我试图打印这两个递归方法时,我得到了一个“void type not allowed here”错误。这两个方法存储在一个binarytree类中,但是需要由驱动程序从binarysearchtree调用,我使用了super.“insert method name”(在下面找到了它的接口)。
驱动程序(最后两个打印语句出错):
package driver;
import java.io.*;
import java.util.*;
public class Driver {
private static Scanner file;
static PrintWriter outputFilePrinter;
static Scanner inputFileScanner;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile; //Declaring scanner obj
PrintWriter printWriter = new PrintWriter("output.txt"); //Text file where results are printed to
inFile = new Scanner(new File("input.txt")); //Text file where student names and associated number are read from
BinarySearchTreeInterface<String> aTree = new BinarySearchTree<>() {}; //Giving access to BinarySearchTree methods
while (inFile.hasNext()) { //Scans input file
String name = inFile.nextLine(); //Assigns contents to string obj
aTree.add(name); //Add string to a tree
} //End while
Iterator<String> traverse = aTree.getPreorderIterator(); //Using iterator to print tree in an "preorder" fashion
while (traverse.hasNext())
printWriter.println(traverse.next()); //Prints tree
printWriter.println("Postorder Recursive: " + aTree.postorderTraverse());
printWriter.println("Inorder Recursive: " + aTree.inorderTraverse());
printWriter.close(); //Closes file
} //End Main
} //End Driver
binarytree类递归方法:
public void inorderTraverse() {
inorderTraverse(root);
}
public void inorderTraverse(BinaryNode<T> node) {
if (node != null) {
inorderTraverse(node.getLeftChild());
System.out.println(node.getData());
inorderTraverse(node.getRightChild());
}
}
public void postorderTraverse() {
postorderTraverse(root);
}
public void postorderTraverse(BinaryNode<T> node) {
if (node != null)
return;
postorderTraverse(root.getLeftChild());
postorderTraverse(root.getRightChild());
System.out.println(root.getData());
}
binarysearchtree类,其中我使驱动程序可以访问两个递归方法:
public void inorderTraverse() {
super.inorderTraverse();
}
public void postorderTraverse() {
super.postorderTraverse();
}
binarysearchtreeinterafce:如何在接口中列出它们
public void postorderTraverse();
public void inorderTraverse();
2条答案
按热度按时间chhkpiq41#
flvlnr442#
binarysearchtree类中的inordertraverse()和postordertraverse()不会返回printwriter.println所期望的字符串。
将返回类型从void更改为string,并从超类返回结果:
别忘了在界面上也做些改变