2

単方向リストのツリーとして実装された Tree が与えられます。insertPath 関数はサブツリーを作成 (または既存のサブツリーを使用) して、filePathQueueintoで表される新しいファイルを格納しますTree<FileNode> t。キューには order がありますIN -> [ “myFile” , “mySubDir” , “myDir” ] -> OUT。つまり、デキューして親ディレクトリを順番に取得し、ツリーの現在のレベルをチェックして、ディレクトリが存在するかどうかを確認できます。各 FileNode には、その名前である値と、trueそれがファイルであることを示すブール値、およびfalseディレクトリであることを示すブール値があります。insertPath のコードと findChild コードを貼り付けました。残りは私たちに与えられたもので、教授提供のコードが機能していると思います。私が実装した唯一のコードは、findChild と insertPath です。

コードが作業フォルダーの「サンプル」ディレクトリを使用して新しいファイル システムを作成すると、例外がスローされます。明確にするために、コンストラクターは、ループ内のツリーに変換しようとしているディレクトリ内のファイルとフォルダーのそれぞれを表す個別のキューを私に渡します。そのため、insertPath は複数回呼び出され、更新されたツリーが毎回渡されます。

ツリーに追加すると例外がスローされる理由がわかりません。空のキューをデキューしようとしていることを示していますが、コードに基づいて、キューが空の場合はそこから戻る必要がありますか? 例外は一番下にあります。問題のある行は、insertPath メソッドの再帰呼び出しと先頭のデキューです。どんな助けでも大歓迎です。ありがとう。

public Tree<T> findChild(T otherLabel) {
    if(getFirstChild() == null)
        return null;
    if(getFirstChild().getLabel() == otherLabel)
        return getFirstChild();
    Tree<T> test = getNextSibling();
    while(test != null){
        if(test.getLabel() == otherLabel)
            return test;
        test = test.getNextSibling();
    }
    return null;
}

public void insertPath(Tree<FileNode> t, QueueList<String> filePathQueue) {
try{
    String check = filePathQueue.dequeue();
    if(filePathQueue.size() == 0){
        Tree<FileNode> file = new Tree<FileNode>(new FileNode(check,false));
        t.addChild(file);
        return;
    }
    Tree<FileNode> dir = new Tree<FileNode>(new FileNode(check,true));
    Tree<FileNode> subdir = t.findChild(dir.getLabel());
    if(subdir == null){
        t.addChild(dir);
        insertPath(t.getFirstChild(), filePathQueue);
    }
    insertPath(subdir, filePathQueue);

    } 
catch(Exception e){ e.printStackTrace(); return;}

InvalidOperationException: Queue empty: nothing to dequeue.
at QueueList.dequeue(QueueList.java:39)
at FileSystem.insertPath(FileSystem.java:38)
at FileSystem.insertPath(FileSystem.java:50)
at FileSystem.insertPath(FileSystem.java:48)
4

1 に答える 1

1

メソッドの最後でinsertPath()再帰的に2 回呼び出しています。insertPath()

public void insertPath(Tree<FileNode> t, QueueList<String> filePathQueue) {
    ...
    if(subdir == null){
        t.addChild(dir);
        insertPath(t.getFirstChild(), filePathQueue); // ONCE
    }
    insertPath(subdir, filePathQueue); // TWICE
}

したがって、filePathQueue要素が 1 つしかない上記のコード ブロックに入ると、これらの呼び出しのそれぞれが 1 つinsertPath()を引き出そうとし、2 つ目はInvalidOperationException質問で示した をスローします。

when is not nullのelseブロックを含めるか、メソッドの最初の行を改善して、アイテムをデキューするにサイズを確認したいようです。subdirinsertPath()filePathQueue

しかし、これは宿題なので、どちらの道を選ぶかはあなたにお任せします。:-)

于 2013-11-05T23:31:56.133 に答える