有人可以帮我从文件中读取并创建二叉树吗?
我的代码是这样但我得到错误。
public static BinaryTreeNode<String> readTree(String filename) {
try {
Scanner s = new Scanner(new File(filename));
return readTree(s);
} catch (FileNotFoundException e) {
System.out.println("Could not find file.");
}
return null;
}
public static BinaryTreeNode<String> readTree(Scanner s) {
String data = s.nextLine().trim(); //ERROR HERE
BinaryTreeNode<String> left = readTree(s);
BinaryTreeNode<String> right = readTree(s);
BinaryTreeNode<String> root = new BinaryTreeNode<String>(data,left,right);
return root;
}
答案 0 :(得分:0)
使用hasNextLine
确保文件至少包含一行
public BinaryTreeNode<String> readTree(Scanner scanner) {
if (scanner.hasNextLine()) {
...
return new BinaryTreeNode<String>(data, left, right);
}
throw new IllegalStateException("No data found to create a BinaryTreeNode");
}