变量在字典中变为常量(java openclassroom)



我正在通过OpenClassroom学习Java,但我在字典上有一个问题。题目让我把变量转换成常数。我必须使用private static final和变量:private final static months.put("June", 6);

理论上这是简单和容易的,但我有这个:error: illegal start of expression

如果我试图改变在public static final不工作..

整个代码:

import java.util.*;
public class MonthsMap {

public static void main(String[] args) {
Map<String, Integer> months = new HashMap <String, Integer>();   

//TODO Remplacez les variables par des constantes
months.put("June", 6);
months.put("September", 9);
months.put("March", 5);

//TODO Corrigez "march" (mars) par sa vraie valeur (3)

//TODO Supprimez "june" (juin)

//Affiche le contenu du dictionnaire
System.out.println("Here are some interesting months");
for (Map.Entry<String,Integer> month : months.entrySet()){
System.out.println(month.getKey() + " is month number " + month.getValue() + " of the year ");
}
}   
}

我想知道为什么它不工作,请帮助我:)

唯一可以应用于局部变量的修饰符是final:

final Map<String, Integer> months = new HashMap<String, Integer>();

如果你想把它改成private static final,你必须把这个局部变量转换成一个成员:

public class MonthMap {
private static final Map<String, Integer> months = new HashMap<String, Integer>();
static {
months.put("June",6);
months.put("September",9);
months.put("March",5);
}
public static void main(String[] args) {
/// Code goes here...
}
}

或者,Java 9中引入的Map.of方法可以允许您将初始化转换为单个语句:

private static final Map<String, Integer> months =
Map.of("June", 6, "September", 9, "March", 5);

很难知道一些第三方网站在要求什么。我怀疑他们希望将那些String和int字面值定义为常量。常量是在类中定义的,而不是在方法中定义的。

public class MonthMap {
public static final String JAN_NAME = "January";
public static final String FEB_NAME = "February";
... etc ... 
public static final int JAN_NUM = 1;
public static final int FEB_NUM = 2;
... etc... 
Map<String, Integer> months = new HashMap <String, Integer>(); 
static {
months.put(JAN_NAME, JAN_NUM);
months.put(FEB_NAME, FEB_NUM);
... etc ...
}
}

最新更新