我得到了一组看起来像这样的字符串(菜单项的路径)
/home
/about
/about/staff
/about/staff/sector1
/about/staff/sector2
/products
/products/section1
我需要以菜单的层次结构这样显示的方式打印它们:
.home
.about
....staff
.......sector1
.......sector2
.products
....section1
这是我的代码:
void printItem(int indent, String path)
{
for(int i=0; i<indent; i++)
{
System.out.print(".");
}
String [] items = null;
if(path.contains("/"))
{
items = path.split("/");
for(int i=0; i<items.length; i++)
{
System.out.println(items[i]);
printItem(indent+3, items[i]);
}
}
else
return;
}
我的代码存在的问题是我不知道如何阻止它多次打印同一父对象。例如,假设我有以下3条路径:
/about
/about/staff
/about/staff/sector1
我最终得到以下输出:
..about
....staff
.....about
....staff
....sector1
....
关于如何摆脱这个问题的任何想法?