Reputation: 3260
Hi I am trying to list folders in unix "ls" command style in java. I have a folder tree like this :
My file structure is as follows :
private class Node{
public List<Node> children= new ArrayList<Node>();
public String value;
public Node(String value){
this.value = value;
}
public void addSubDirectory(Node child){
children.add(child);
}
}
Problem : I am not able to recurse more than the children of current folder when there is nothing after the ' * ' in a command
For eg. command
ls A/B/*/*/E/ and ls A/*/*/M/*/E/ works
But command " ls A/ * " only shows
B Y
Code to traverse
public void showCommand(Node root, String command){
String argument = command.substring(3);
System.out.println("command is ls "+argument);
show(root,argument);
}
private void show(Node root, String cmd){
int N = cmd.length();
if(N==0){
// case when end of command is reached
for(Node child:root.children){
System.out.println(child.value);
}
}else{
char c = cmd.charAt(0);
// case when folder name is present in command
if((c!='*') && (c!='/')){
for(Node child:root.children){
if(child.value.equals(String.valueOf(c))){
show(child,cmd.substring(1));
}
}
return;
}else if(c=='*'){
// case when * is present in command
// i think problem lies here
if(N==1){
System.out.println(root.value);
preOrderTraverse(root);
}else{
for(Node child:root.children){
show(child,cmd.substring(1));
}
}
return;
}else if(c=='/'){
// case when '/' is present in commmand
show(root,cmd.substring(1));
return;
}
}
}
Upvotes: 0
Views: 522
Reputation: 693
When the last char in the command is a *, you call back the showCommand
method with an empty cmd and when the method receives an empty cmd string the recursion stops.
When the current char c
is a *, you should check it's the last char in cmd
, if it is then you should send the current cmd
instead of cmd.substring(1)
. That way it should go through the hierarchy recursively.
Upvotes: 1