java - 字典中的变量到常量(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...
}
}
或者,Map.of
Java 9 中引入的方法可以允许您将初始化转换为单个语句:
private static final Map<String, Integer> months =
Map.of("June", 6, "September", 9, "March", 5);
推荐阅读
- django - 如何过滤一组值的字段
- swift - libsybdb.a(dblib.o)' 不包含位码
- python - 如何使用python确定两个图中的峰值并仅绘制两个图中的峰值图
- node.js - 如何在 docker 容器中配置节点应用程序和 haProxy?
- postgresql - 根据条件拆分为多列
- java - Spring Boot JAR 应用程序未从资源文件夹中读取 chromedriver.exe
- hyper-v - Enable-PSRemoting (Set-WSManQuickConfig) 和 HyperV 适配器
- java - Spring Kafka:记录侦听器与批处理侦听器
- image-processing - C++ 从位图中获取图像缓冲区
- c - C 库应该如何管理错误?