在我的应用程序中,我动态地获得了字符串值。我想将这些值分配给字符串数组然后打印这些值。但它显示错误(空指针异常) 例如:
String[] content = null;
for (int s = 0; s < lst.getLength(); s++) {
String st1 = null;
org.w3c.dom.Node nd = lst.item(s);
if (nd.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
NamedNodeMap nnm = nd.getAttributes();
for (int i = 0; i < 1; i++) {
st1 = ((org.w3c.dom.Node) nnm.item(i)).getNodeValue().toString();
}
}
content[s] = st1;
//HERE it shows null pointer Exception.
}
谢谢
最佳答案
这是因为您的字符串数组为空。 String[] content=null;
您将数组声明为 null,然后尝试在其中赋值,这就是它显示 NPE 的原因。
您可以尝试为字符串数组提供初始大小或更好地使用 ArrayList<String>
.
即:
String[] content = new String[10]; //--- You must know the size or array out of bound will be thrown.
如果你像这样使用 arrayList 会更好
List<String> content = new ArrayList<String>(); //-- no need worry about size.
对于列表使用 add(value)
在列表中添加新值并使用 foreach
的方法循环打印列表的内容。
关于JAVA-如何动态地将字符串值分配给字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6054261/