I am trying to write a class that has methods according to a homework assignment. The class input is a string that is turned into an char array. I want to return the char array as a string inside the method originalChar. Here is my code:
public class Problem5 {
public static void main(String[] args) {
CharacterArray array1 = new CharacterArray("Cool");
System.out.println(array1.originalChar());
}
}
class CharacterArray {
char[] storage;
String formForReturn;
CharacterArray() {
}
CharacterArray(String s) {
char[] storage = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
storage[i] = s.charAt(i);
}
}
public String originalChar() {
String formForReturn = new String(storage);
return formForReturn;
}
}
The error I get is NullPointerException, which to my understanding means I am trying to reference something that doesn't exist. I'm not sure how I troubleshoot this and how to resolve this problem. Some help would be much appreciated.
char[] storageis wrong. Because you create anotherstoragewhich is just in that method. You should usethis.storageor just removechar[]