Java – ArrayList. Java that causes NullPointerException Add() method
•
Java
The longinteger class causes the following error at runtime:
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)
Here are some excerpts from relevant courses:
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 } }
I don't know what caused this NullPointerException Does anyone have any suggestions?
Solution
You will never instantiate storedstrings Try to change:
private ArrayList<String> storedStrings;
To:
private ArrayList<String> storedStrings = new ArrayList<String>();
If you have this line:
this.storedStrings.add(0,s);
It is calling the method add < string > on the ArrayList instance, which is stored in this In storedstrings New operators are the way you get new things
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码