akolangto
akolangto

Reputation: 33

Why do I get this error " Syntax error on token ";", { expected after this token "

I am currently facing this error and I don't know why this is happening. When I try to add a value to my array, this error comes up and I don't know why and how.

This is the part of the code where I get the error:

class DateFormatSymbols{
    String[] monthNames = new String[11];
    String[] weekDays = new String[6];
    
    monthNames[0] = "January";  
}

This is the whole code, its not finished yet because of this error.

public class Calendar {

        private static int day;
        private static int month;
        private static int year;
        
        public static void main(String[] args) {
            
    
        }
    
        public static int getDay() {
            return day;
        }
    
        public static void setDay(int day) {
            Calendar.day = day;
        }
    
        public static int getMonth() {
            return month;
        }
    
        public static void setMonth(int month) {
            Calendar.month = month;
        }
    
        public static int getYear() {
            return year;
        }
    
        public static void setYear(int year) {
            Calendar.year = year;
        }
    
    }
    class DateFormatSymbols{
        String[] monthNames = new String[11];
        String[] weekDays = new String[6];
        
        monthNames[0] = "January";  
    }

Upvotes: 0

Views: 55

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86391

You have a statement in a class body.

class DateFormatSymbols{
    String[] monthNames = new String[11]; <-- Field declaration with an initializer
    String[] weekDays = new String[6];

    monthNames[0] = "January";  // <-- Statement
} 

You could move the statement into a constructor.

class DateFormatSymbols{
    String[] monthNames = new String[11];
    String[] weekDays = new String[6];

    DateFormatSymbols() {   // <-- Constructor
        monthNames[0] = "January";  
    }
} 

Or you could put it in an instance initializer block.

class DateFormatSymbols{
    String[] monthNames = new String[11];
    String[] weekDays = new String[6];

    {    // <-- Initializer block called for each instance
        monthNames[0] = "January";  
    }
} 

Upvotes: 2

Related Questions