Java 行走树-标记值的长度
这是我试图解决的问题。 我有一个简单的HTML页面:Java 行走树-标记值的长度,java,string,tree,sum,Java,String,Tree,Sum,这是我试图解决的问题。 我有一个简单的HTML页面: <html> <head></head> <body> <table> <tr> <td>Hello</td> <td>World</td> </tr> <tr> <t
<html>
<head></head>
<body>
<table>
<tr>
<td>Hello</td>
<td>World</td>
</tr>
<tr>
<td>Goodby</td>
<td>World</td>
</tr>
</table>
</body>
我将根节点传递给这个方法。这段代码的问题在于它只返回路径的长度。这意味着我得到了这样的东西:
<html>
<head></head>
<body>
<table>
<tr>
<td>Hello</td> // console output is string of length: 5
<td>World</td> // console output is string of length: 10
</tr>
<tr>
<td>Goodby</td> // console output should be string of length: 6 <-- does not consider overall length of previous <tr> content
<td>World</td> // console output should be string of length: 11
</tr>
</table>
</body>
你好//控制台输出是长度为5的字符串
World//控制台输出为长度为10的字符串
Goodby//console输出应该是长度为6的字符串:计数器是通过值传递的(不是通过引用),因此从递归调用的方法向其添加值不会影响调用方法中的值。您可能希望将aCounter
的新值返回给调用方法,以便它可以更新自己的版本
像这样的方法应该会奏效:
private static void print(Node aNode, int aCounter, String aIndent)
{
if(aNode.getNodeValue() != null)
System.out.println(aIndent+aNode.getNodeName() + ", "+aNode.getNodeValue() + ", length: " + aCounter);
else
System.out.println(aIndent+aNode.getNodeName());
Node child = aNode.getFirstChild();
while (child != null)
{
if(child.getNodeValue() != null)
{
aCounter += child.getNodeValue().length();
}
aCounter = print(child, aCounter, aIndent+" ");
child = child.getNextSibling();
}
return aCounter;
}
(尽管您可能想重新考虑变量和方法的名称,使其更具可读性。)谢谢Mattias!就这样。我也听从了你的建议,选择了更有意义的方法/变量名。只需单击答案左侧的复选标记即可。;-)
<html>
<head></head>
<body>
<table>
<tr>
<td>Hello</td> // console output is string of length: 5
<td>World</td> // console output is string of length: 10
</tr>
<tr>
<td>Goodby</td> // console output should be string of length: 6 <-- does not consider overall length of previous <tr> content
<td>World</td> // console output should be string of length: 11
</tr>
</table>
</body>
private static void print(Node aNode, int aCounter, String aIndent)
{
if(aNode.getNodeValue() != null)
System.out.println(aIndent+aNode.getNodeName() + ", "+aNode.getNodeValue() + ", length: " + aCounter);
else
System.out.println(aIndent+aNode.getNodeName());
Node child = aNode.getFirstChild();
while (child != null)
{
if(child.getNodeValue() != null)
{
aCounter += child.getNodeValue().length();
}
aCounter = print(child, aCounter, aIndent+" ");
child = child.getNextSibling();
}
return aCounter;
}