Search code examples
javacurly-braces

Error: error class interface or enum expected in Java class


Unfortunately, I believe I know the issue - I have a brace out of line, but I look through my code and it all seems to be in working order - I've pored over it line by line and cannot find what could be cause this error (I get 19 of them when I run the code as is). Can anyone provide any help? Is there something else I'm missing here? Thank you in advance. Here is my code:

public class DateGenerator
{

    private int month, day;
    private String newDate;
    private String[] monthNames = new String[12];
    private String[] dayNames = new String[7];

    public DateGenerator()
    {
        monthNames = {"Jan", "Feb", "Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"};

        dayNames = {"Mon", "Tues", "Wed", "Thur", "Fri", "Sat", "Sun"};

        month = 1;
    }


    public void setMonth(int m)
    {
        month = m;
        //System.out.println("XXXXXXXXXXXXXXXXXXXSETMONTH IS: " + month);
        calculate();
    }

    public String getRandomDate()
    {
        return newDate;
    }

    private void calculate()
    {
        switch(month)
        {
            case 2: //Feb 1-28 
            day = (int)(Math.random()*28);
            //System.out.println("MADE IT HERE1 and day is " + day);
            break;

            case 4: case 6: case 9: case 11:
            day = (int)(Math.random()*30);
            //System.out.println("MADE IT HERE2 and day is " + day);
            break;

            default:
            day = (int)(Math.random()*31);
            //System.out.println("MADE IT HERE3 and day is " + day);
            break;
        }
        if(day == 0) day = 1;
        int dayn = (int)(Math.random()*7);
        //System.out.println("Dayn is " + dayn); 
        newDate = dayNames[dayn] + ", " + monthNames[month]+ "  " + day;
        //System.out.println(newDate);
    }  

}

Solution

  • The issue is with your array initializers.

    Instead of:

       dayNames = {"Mon", "Tues", "Wed", "Thur", "Fri", "Sat", "Sun"}; 
    

    You should have:

       dayNames = new String[]{"Mon", "Tues", "Wed", "Thur", "Fri", "Sat", "Sun"};
    

    And the same for monthNames.

    The way you set these arrays would only work at declaration time. Assuming you need to set them in the class's constructor, they cannot be set that way.

    And

    private String[] monthNames = new String[12];
    private String[] dayNames = new String[7];
    

    can be replaced by:

    private String[] monthNames;
    private String[] dayNames;
    

    unless you have another constructor that doesn't set them in the future. This is to avoid a useless allocation as each of these fields receive a new array created in the constructor anyway.