単方向リストのツリーとして実装された Tree が与えられます。insertPath 関数はサブツリーを作成 (または既存のサブツリーを使用) して、filePathQueue
intoで表される新しいファイルを格納します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)