给我们一些树,实现为单链列表树。所述insertPath函数构造一个子树(或使用现有的子树)来存储一个新的文件,由下式表示filePathQueue
成Tree<FileNode> t
。队列有一个order IN -> [ “myFile” , “mySubDir” , “myDir” ] -> OUT
,这意味着我应该能够出队以按顺序获取父目录,然后对照树中的当前级别检查目录是否存在。每个FileNode都有一个值,即其名称,以及一个布尔值true
,指示它是一个文件,并false
指示它是一个目录。我已经粘贴了我的代码insertPath以及findChild代码。其余的都交给了我们,我认为教授提供的代码正在工作。我实现的唯一代码是findChild和insertPath。
当代码使用我的工作文件夹中的“ sample”目录创建一个新的FileSystem时,将引发该异常,该目录包含三个子目录,每个子目录包含一些文件和它们自己的子目录。澄清一下:构造函数将代表我将要循环转换为树的目录中每个文件和文件夹的单独队列传递给我。因此,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)
您在方法末尾insertPath()
递归调用两次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
只有一个元素的a进入上述代码块,则对这些调用中的每一个insertPath()
都将尝试拉出其中一个,而第二个调用将把InvalidOperationException
您在问题中展示的代码抛出。
看来你要么需要包括else
用于当块subdir
是不为空,或者提高你的第一线insertPath()
方法来检查filePathQueue
大小之前,您试图从它出队的项目。
但是,既然这是家庭作业,我就让您决定走哪条路。:-)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句