首页 > 解决方案 > 为什么我会收到此错误“令牌上的语法错误”;“,{此令牌后预期”

问题描述

我目前正面临这个错误,我不知道为什么会这样。当我尝试向我的数组添加一个值时,会出现这个错误,我不知道为什么以及如何。

这是我收到错误的代码部分:

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

这是整个代码,由于这个错误,它还没有完成。

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";  
    }

标签: javaarrays

解决方案


您在类主体中有一个声明。

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

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

您可以将语句移动到构造函数中。

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

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

或者你可以把它放在一个实例初始化块中。

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

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

推荐阅读