【发布时间】:2014-03-11 05:21:35
【问题描述】:
我有一个需要使用 java 解析的缩进文件, 我需要一些方法将它放在 Section 类中,如下所示
root
root1
text1
text1.1
text1.2
text2
text2.1
text2.2
root2
text1
text1.1
text1.2
text2
text2.1
text2.2.2
我有一个类来放置看起来像缩进的东西
public class Section
{
private List<Section> children;
private String text;
private int depth;
public Section(String t)
{
text =t;
}
public List<Section> getChildren()
{
if (children == null)
{
children = new ArrayList<Section>();
}
return children;
}
public void setChildren(List<Section> newChildren)
{
if (newChildren == null) {
children = newChildren;
} else {
if (children == null) {
children = new ArrayList<Section>();
}
for (Section child : newChildren) {
this.addChild(child);
}
}
}
public void addChild(Section child)
{
if (children == null) {
children = new ArrayList<Section>();
}
if (child != null) {
children.add(child);
}
}
public String getText()
{
return text;
}
public void setText(String newText)
{
text =newText;
}
public String getDepth()
{
return depth;
}
public void setDepth(int newDepth)
{
depth = newDepth;
}
}
我需要一些方法来解析文件并将其放置在预期结果中,我们是一个 Section 对象,如下所示
Section=
Text="Root"
Children
Child1: Text= "root1"
Child1: "text1"
Child1="Text 1.1"
Child2="Text 1.2"
Child2: "text2"
Child1="Text 2.1"
Child2="Text 2.2"
Children
Child2: Text= "root2"
Child1: "text1"
Child1="Text 1.1"
Child2="Text 1.2"
Child2: "text2"
Child1="Text 2.1"
Child2="Text 2.2"
Here is some code that I have started
int indentCount=0;
while(String text = reader.readline()
{
indentCount=countLeadingSpaces(String word);
//TODO create the section here
}
public static int countLeadingSpaces(String word)
{
int length=word.length();
int count=0;
for(int i=0;i<length;i++)
{
char first = word.charAt(i);
if(Character.isWhitespace(first))
{
count++;
}
else
{
return count;
}
}
return count;
}
【问题讨论】:
-
看起来你可以通过计算
Section前面的空格来检测它的深度。因此,如果深度大于前一行的深度,则将其添加为Section的子代,否则将其创建为新的Section。顺便说一句,您可能需要以下两者之一:(i) parent 字段,或 (ii) depth 字段。 -
您发布的代码并没有真正尝试解决您所询问的问题。您是否编写了一些代码来尝试解决上述问题?
-
@Dukeling 刚刚编辑了它
-
@Chthonic Project 我刚刚添加了深度场。