-2

I have two classes

I am not sure why this is erroring. In eclipse there are no red underlines.

Main:

package com.example;

public class Main {
    public static void main(String[] args) {
        Week myWeek = new Week(Week.days.FRIDAY);
        System.out.println(myWeek.Today.toString());
    }
}

Week:

package com.example;

public class Week {
    public static enum days {
        SUNDAY,
        MONDAY,
        TUESDAY,
        WEDNESDAY,
        THURSDAY,
        FRIDAY,
        SATURDAY
    }

    static final days[] order = {
        days.SUNDAY, days.MONDAY, days.TUESDAY, days.WEDNESDAY, 
        days.THURSDAY, days.FRIDAY, days.SATURDAY
    };
    days Today;

    Week(days toSetTo){
        @SuppressWarnings("unused")
        days Today = toSetTo;
    }
}

the error is on Main.java:6

  • where is the variable in the constructor stored? – n247s Aug 29 '16 at 19:23
  • 2
    Now is the time to start using Java code conventions; they make communication much simpler. Capitalize classes (including enums), constants in `ALL_CAPS`, variables in `camelCase`. – chrylis -cautiouslyoptimistic- Aug 29 '16 at 19:25
  • You are declaring two variables for `Today`, one variable is local to the constructor, and the other is the instance variable. You should always use `this.varName` to reference an instance variable. – 4castle Aug 29 '16 at 19:27
  • Proper dupe: [Why does Java throw NullPointerException here?](http://stackoverflow.com/q/30567802) – Tom Aug 29 '16 at 19:31

2 Answers2

1

The following is failing at runtime:

myWeek.Today.toString()

because myWeek.Today is null.

In your constructor instead of:

days Today = toSetTo;

you need to do this:

Today = toSetTo;

rohitvats
  • 1,811
  • 13
  • 11
0

You should have fixed the unused warning properly instead of suppressing it. Remove the word days in that line. And look closely at the colors of the variables in Eclipse. They tell you which names belong to each other.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121