首页 > 解决方案 > 字典中的变量到常量(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 ");
        }
    }   
}

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

标签: java

解决方案


您可以应用于局部变量的唯一修饰符是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...
    }
}

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

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

推荐阅读