gpt4 book ai didi

java - ArrayList.add() 方法导致 NullPointerException

转载 作者:搜寻专家 更新时间:2023-11-01 01:02:26 25 4
gpt4 key购买 nike

LongInteger 类在运行时导致以下错误:

Exception in thread "main" java.lang.NullPointerException
at LongInteger.breakString(LongInteger.java:38)
at LongInteger.<init>(LongInteger.java:17)
at LongInteger.main(LongInteger.java:149)

以下是一些相关的类(class)摘录:

public class LongInteger extends Object {
private ArrayList<String> storedStrings;


// Constructor
public LongInteger(String s) {
this.setInputString(s);
this.breakString(this.inputString); //Exception @ line 17
}

/**
* the purpose of this method is to break the input string into an
* ArrayList<String> where each String has a length of 9 or less.
*/
private void breakString(String s){
if(s.length()>9){
storedStrings.add(0,s.substring(s.length()-9,s.length()));
this.breakString(s.substring(0,s.length()-9));
} else {
this.storedStrings.add(0,s); //Exception @ line 38
}
}


public static void main(String[] args) {
LongInteger a = new LongInteger("12345"); //Exception @ line 149
}
}

我不知道是什么导致了这个 NullPointerException。有人有什么建议吗?

最佳答案

你永远不会实例化 storedStrings .尝试更改:

private ArrayList<String> storedStrings;

收件人:

private ArrayList<String> storedStrings = new ArrayList<String>();

当你有线路时:

this.storedStrings.add(0,s);

它正在调用方法 addArrayList<String>实例上存储在 this.storedStrings . new运算符是您获取事物新实例的方式。

关于java - ArrayList.add() 方法导致 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9304260/

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