java - 为什么我会收到此错误“令牌上的语法错误”;“,{此令牌后预期”
问题描述
我目前正面临这个错误,我不知道为什么会这样。当我尝试向我的数组添加一个值时,会出现这个错误,我不知道为什么以及如何。
这是我收到错误的代码部分:
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";
}
解决方案
您在类主体中有一个声明。
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";
}
}
推荐阅读
- kubernetes - 如何与同一 k8s 集群中的 pod 内的 Kubernetes CRD 服务通信?
- r - 将一个单元格数据拆分为两个变量,然后保存在 csv 中
- javascript - Javascript String Array-Like-Object behaviour
- python - 更好地映射辅助函数或父函数?
- docker - Docker:使用自定义退出代码退出
- python - 遍历键值对列表并使用 Python 获取特定的键和值
- excel - Talend 导入、转换原始文件并导出为 CSV
- python - 在 Python 中重命名文件,获取 FileNotFoundError
- python - aiohttp ClientSession.get() 方法静默失败 - Python3.7
- dialogflow-es - 是否有一种简单的方法可以在对话流中创建“电影名称”实体