-2

Its rough right now, but I'm stuck because I can't find a way to access either digits (an array of integers (it has to be a private array, per the assignment rules)) or size. Is there a way to access constructor variables in methods within the same class?

I'm not sure what to try, as I'm still in the very basic stages (only a lesson or two in Java) and I don't know how to continue.

public class Zillion {
    private int[] digits;
    String strdigits;
    public Zillion(int size) {
        int[] digits = new int[size];
}
public String toString() {
    for(int x=0; x<digits.length; x++) {
        strdigits += digits[x];
        System.out.println(strdigits);
    }
    return(strdigits);
}

public static void main(String[] args) {
    Zillion z = new Zillion(2);   
    System.out.println(z);  //  00  2 points


}

}

Below are my errors; System.out.println(z) is supposed to output 00, but it seems the code gets trapped by a NullPointerException when I try to access digits.length in line 10.

Exception in thread "main" java.lang.NullPointerException
    at lab4_carl6188.Zillion.toString(Zillion.java:10)
    at java.base/java.lang.String.valueOf(String.java:3042)
    at java.base/java.io.PrintStream.println(PrintStream.java:897)
    at lab4_carl6188.Zillion.main(Zillion.java:19)

2 Answers2

0

int[] digits = new int[size]; shadows the class field digits Change to digits = new int[size];

Ending up with a constrcutor

public Zillion(int size) {
        digits = new int[size];
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

The problem is with your definition of Constructor, you are initializing a local variable digits and that's why you get null pointer exception :

public Zillion(int size) {
        int[] digits = new int[size];
}

you should rewrite your constructor as follows :

public Zillion(int size) {
        digits = new int[size];
}

in this new constructor the global variable digits is initializing

Mohsen_Fatemi
  • 2,183
  • 2
  • 16
  • 25