我有一个如下格式的 XML;
<TestCase>
<Step Sel = "deleteAllVisibleCookies" Obj = "All cookies" Val = ""></Step>
<Step Sel = "open" Obj = "URL" Val = "UserName:Password"></Step>
<Step Sel = "waitForElementPresent" Obj = "link=mobile" Val = ""></Step>
<Step Sel = "clickAndWait" Obj = "Mobile link" Val = ""></Step>
...
</TestCase>
<TestCase>
<Step Sel = "deleteAllVisibleCookies" Obj = "All cookies" Val = ""></Step>
<Step Sel = "open" Obj = "URL" Val = "UserName:Password"></Step>
<Step Sel = "waitForElementPresent" Obj = "link=mobile" Val = ""></Step>
<Step Sel = "clickAndWait" Obj = "Mobile link" Val = ""></Step>
...
</TestCase>
基于上面的 XML 文件,我正在创建一个对象。我试图将所有步骤保存到二维数组中。所以一行是一个测试用例。
int i=0;
int j=0;
for (int TC = 0; TC < TCLst.getLength(); TC++)
int k=0;
Node TCLstNode = TCLst.item(TC);
if (TCLstNode.getNodeType() == Node.ELEMENT_NODE)
{
NodeList StepLst = TCLstNode.getChildNodes();
Step = new String [TCCount][StepLst.getLength()];//defining total length
Sel = new String [TCCount][StepLst.getLength()];
Obj = new String [TCCount][StepLst.getLength()];
Val = new String [TCCount][StepLst.getLength()];
for (int Step = 0; Step < StepLst.getLength(); Step++)
{
Node StepLstNode = StepLst.item(Step);
if (StepLstNode.getNodeType() == Node.ELEMENT_NODE)
{
if (StepLstNode.getNodeName() == "Step")
{
Sel[i][k] = ObjectType.getAttribute(StepLstNode,"Sel");//returns value of Sel attribute
Obj[i][k] = ObjectType.getAttribute(StepLstNode,"Obj");
Val[i][k] = ObjectType.getAttribute(StepLstNode,"Val");
stepCountInTC++;
k++;
}
}//NodeType
}//for
i++;
stepCountInATCOfModule[j] = stepCountInTC;
j++;
stepCountInTC = 1;
}//TC if
我面临的问题是在创建对象之后,在打印任何二维数组时,我得到的输出为(这里我使用了 Sel 属性);
[[null, null, null, null,...][deleteAllVisibleCookies, open, waitForElementPresent, clickAndWait,...]]
这里的问题是第一个测试用例值保存为空。如果我使用带有 3 个测试用例的 XML,那么前 2 个测试用例将保存为 null,第三个测试用例将正确保存到数组中。
另请建议使用任何集合来代替二维数组。
最佳答案
你错过了这里的大括号:
for (int TC = 0; TC < TCLst.getLength(); TC++)
int k=0;
这两行之后的代码与此 for
无关,因为 java 认为您这样做:
for (int TC = 0; TC < TCLst.getLength(); TC++) {
int k=0;
}
因此 k
将始终为 0
。
您的代码存在多个问题需要修复。例如:
Step = new String [TCCount][StepLst.getLength()];
和
int Step = 0
Step
是一个 int
或其他东西(在代码中不可见),将它们混合起来并不是一件好事。您也没有使用camelCase
变量名称。
关于Java - 二维数组 - 只有数组最后一行的值被正确分配,其余的被分配为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921846/