Hi, I'm a novice. I want to understand why this code will not work. This is an exercise in implementing interfaces, and I've missed something fundamental. If I invoke a method (say charAt) from another class, it fails with nullpointer exception, because mySeg cannot be instantiated from within the constructor (in my code). The only way I've tried that works is instantiating mySeg within every method. e.g Segment mySeg = new Segment(jarray,0,jlen); at the start of the method. Surely, the object mySeg will exist after the constructor when the class is instantiated with:-
char[] testArray = {'\u0054','\u0048','\u0049','\u0053'};
CharSeqPlus myCS = new CharSeqPlus(testArray,4);
The problem class is:-
Thanks for your help. It must be very fundamental!public class CharSeqPlus implements CharSequence{ char[] jarray; int jlen; Segment mySeg; /* Constructor */ public CharSeqPlus(char[] arrayIn, int lenIn) { jarray = arrayIn; jlen = lenIn; Segment mySeg = new Segment(jarray,0,jlen); /* in the other methods, mySeg is not instatiated after */ /* this statement, so do a new one in each method! */ } public char charAt(int locIn){ Segment mySeg = new Segment(jarray,0,jlen); return mySeg.charAt(locIn); } public int length(){ Segment mySeg = new Segment(jarray,0,jlen); return mySeg.length(); } public CharSequence subSequence(int stIn, int enIn){ Segment mySeg = new Segment(jarray,0,jlen); return mySeg.subSequence(stIn,enIn); } public String toString(){ Segment mySeg = new Segment(jarray,0,jlen); return mySeg.toString(); } public String reversed(){ Segment mySeg = new Segment(jarray,0,jlen); String revString = ""; for(int i=jlen-1;i>=0;i--) { revString = revString + jarray[i]; } return revString; } } //class