gpt4 book ai didi

java - 为什么我要为String数组获取java.lang.NullPointerException?

转载 作者:行者123 更新时间:2023-12-03 08:55:38 25 4
gpt4 key购买 nike

不确定我为什么要为String数组获取java.lang.NullPointerException吗?我看了几个小时,却找不到任何问题。请帮忙

private String[] stringList;
int j = 0;
StringClass stringRef = new StringClass();

while (//As long as there is string available from what I am reading in)
{
str = //String read in;
stringRef.setString(str);
stringList[j] = stringRef.returnString(); //Shows that this line is the error
j++;
}

这是类(class):
public class StringClass {

private String stringNew;

public void setString(String newStr){
stringNew = newStr;
}

public String returnString(){
return stringNew;
}
}

最佳答案

即使它是变量List的名称,也没有使用stringList。列表将动态调整大小,因此您不必在编译时声明初始大小。

这是您的代码以及我建议的更改:

import java.util.ArrayList;
import java.util.List;

...

private List<String> stringList = new ArrayList<String>();
int j = 0;
StringClass stringRef = new StringClass();

while (//As long as there is string available from what I am reading in)
{
str = //String read in;
stringRef.setString(str);
stringList.add(stringRef.returnString()); //Shows that this line is the error
j++;
}

关于java - 为什么我要为String数组获取java.lang.NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com