enum Week1{ Monday("星期一"),Tuesday("星期二"),Wednesday("星期三"),Thursday("星期四"),Friday("星期五"),Saturday("星期六"),Sunday("星期日"); private String name; Week1(String name){ this.name = name; } public String toString() { return this.name(); } } public class t2 { public static void main(String[] args) { Week1 wk1 = Week1.Monday; System.out.println("x="+wk1); Week1 wk2 = Week1.valueOf("Tuesday"); System.out.println("Week.valueOf(\"Tuesday\")"+"="+wk2); System.out.println("Week枚举类型的所有取值为:"); for(Week1 wk:Week1.values()) { System.out.println(wk); } } }
时间: 2023-07-13 13:32:16 浏览: 149
这段代码的问题在于,类名和代码中引用的枚举类型名称不一致。
具体来说,枚举类型定义为 Week1,但是在 t2 类中引用时却使用了 Week。所以在 t2 类中,需要将代码中的所有 "Week" 替换为 "Week1",包括 System.out.println("Week.valueOf(\"Tuesday\")"+"="+wk2); 和 for(Week1 wk:Week1.values())。
修改后的代码如下所示:
```
enum Week1{
Monday("星期一"),Tuesday("星期二"),Wednesday("星期三"),Thursday("星期四"),Friday("星期五"),Saturday("星期六"),Sunday("星期日");
private String name;
Week1(String name){
this.name = name;
}
public String toString() {
return this.name();
}
}
public class t2 {
public static void main(String[] args) {
Week1 wk1 = Week1.Monday;
System.out.println("x="+wk1);
Week1 wk2 = Week1.valueOf("Tuesday");
System.out.println("Week1.valueOf(\"Tuesday\")"+"="+wk2);
System.out.println("Week1枚举类型的所有取值为:");
for(Week1 wk:Week1.values()) {
System.out.println(wk);
}
}
}
```
修改后的代码可以正常编译运行,并输出如下结果:
```
x=Monday
Week1.valueOf("Tuesday")=Tuesday
Week1枚举类型的所有取值为:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
```
阅读全文