JAVA-如何将字符串值动态分配给字符串数组

JAVA-如何将字符串值动态分配给字符串数组,java,Java,在我的应用程序中,我动态地获取字符串值。我想将这些值分配给字符串数组,然后打印这些值。但它显示了一个错误(空指针异常) 例: String[]content=null; 对于(int s=0;s

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

String[]content=null;
对于(int s=0;s

谢谢,这是因为您的字符串数组为空<代码>字符串[]内容=空

您将数组声明为null,然后尝试在其中赋值,这就是它显示NPE的原因

您可以尝试为字符串数组指定初始大小,或者更好地使用
ArrayList
。 即:

如果像这样使用arrayList会更好

List<String> content = new ArrayList<String>(); //-- no need worry about size.
List content=new ArrayList();//--不用担心尺寸。

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

使用
ArrayList
Vector
以动态方式创建字符串集合(或数组)

List<String> contents = new ArrayList<String>();
Node node = (org.w3c.dom.Node) nnm.item(i)).getNodeValue();
if (null != node)
    contents.add(node.toString());

要理解你的目标有点困难,因为你的例子被蒙蔽了。但是,字符串数组为空。您需要初始化它,而不仅仅是声明它。您是否考虑过改用ArrayList?java中的数组是固定长度的(除非在我大学时代他们改变了这一点)

使用ArrayList要简单得多

例如:

他们都会打印一次“你好”,就这样。

使用

 content[s] = new String(st1);

现在,它为该特定数组索引创建新实例

您的
for
循环
(int i=0;i<1;i++)
告诉它执行此循环一次。这有点不寻常。您可以删除循环并将内容留在其中,从而获得相同的结果。
List<String> contents = new ArrayList<String>();
Node node = (org.w3c.dom.Node) nnm.item(i)).getNodeValue();
if (null != node)
    contents.add(node.toString());
for(String content : contents) {
     System.out.println(content) // since you wanted to print them out
List<String> content = new ArrayList<String>();
for (int i = 0; i < limit; i++){
   String toAdd;
   //do some stuff to get a value into toAdd
   content.add(toAdd)
}
for(int i=0;i<1;i++)
for(int i=0;i<1;i++){
   System.out.println("hello");
}
System.out.println("hello");
 content[s] = new String(st1);