OpenClassroom Java练习:字典变量转常量报非法表达式错误
报错原因
private/static/final这类修饰符只能用来修饰类的成员属性、成员方法、内部类,不能用在方法内部的局部变量,更不能直接加在months.put()这类方法调用语句的前面,你的写法不符合Java语法规范,因此触发非法表达式报错。- 练习要求的「将变量转换为常量」指的是把存储月份的
monthsMap对象定义为类级别的常量,而非main方法内的局部变量。
额外说明
final修饰集合对象时,仅限制该变量的引用不能指向其他集合对象,集合内部的元素仍支持增删改操作。如果需要完全不可变的集合,可在初始化时用Collections.unmodifiableMap包裹HashMap,后续修改集合内容的操作会直接抛出异常。
修复后的完整代码
import java.util.*; public class MonthsMap { // 按要求定义为类级别的私有静态常量 private static final Map<String, Integer> months = new HashMap<>(); // 静态代码块初始化常量集合的内容 static { months.put("June", 6); months.put("September", 9); months.put("March", 5); } public static void main(String[] args) { // 修正March的值为3 months.put("March", 3); // 删除June months.remove("June"); // 输出集合内容 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 "); } } }
内容的提问来源于stack exchange,提问作者Yumgi
相关产品推荐
相关产品推荐

