JAVA-如何动态地将字符串值赋给字符串数组

use*_*855 4 java

在我的应用程序中,我动态获取字符串值 我想将这些值分配给字符串数组然后打印这些值.但它显示一个错误(空指针异常)EX:

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.
}  
Run Code Online (Sandbox Code Playgroud)

谢谢

Har*_*Joy 8

这是因为您的字符串数组为null. 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.
Run Code Online (Sandbox Code Playgroud)

如果你使用像arrayList更好

List<String> content = new ArrayList<String>(); //-- no need worry about size.
Run Code Online (Sandbox Code Playgroud)

对于列表使用add(value)方法,在列表中添加新值并使用foreach循环打印列表的内容.