nus-cs2113-AY2223S2 / forum

10 stars 0 forks source link

For each loop causes error #18

Open Brennanzuz opened 1 year ago

Brennanzuz commented 1 year ago

With reference to Coursemology Week 4 Q3, if one uses the for each loop for printAreas() like this:

    private static void printAreas() {
        for (Shape shape : shapes) {
            System.out.println(shape.area());
        }
    }

This error will show: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "week_4.Q3.Shape.area()" because "shape" is null Whereas if you used the normal for loop:

   private static void printAreas() {
        for (int i = 0; i < shapeCount; i += 1) {
            System.out.println(shapes[i].area());
        }
    }

It works. Why makes this for each loop different from the for loop?

Magmanat commented 1 year ago

This is because in your first version, since your array starts off as size 100, and you are keeping track of the size of instantiated shapes using "shapeCount". It will automatically iterate from start to end, eventually hitting a null value in that array which has no callable .area().

But in the second version, your for loop is limited by "shapeCount", hence it will not result in this error

okkhoy commented 1 year ago

@Magmanat nice, concise explanation 💯❗