从文件中读取字符串并创建二叉树

时间:2014-04-14 14:25:31

标签: java

有人可以帮我从文件中读取并创建二叉树吗?

我的代码是这样但我得到错误。

   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;
}

1 个答案:

答案 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");
}