我在Java中有点新......
以下是我要实现的Java源代码。
首先,我定义一个这样的公共枚举类:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
现在我创建一个这样的类:
import java.time.*;
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY: case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}
当我编译EnumTest课程时#39;我收到这个错误:
C:\java>javac EnumTest.java
EnumTest.java:4: error: class Day is public, should be declared in a file named
Day.java
public enum Day {
^
1 error
你可以帮帮我吗?
谢谢
梅尔
答案 0 :(得分:3)
您的代码似乎很好,错误显示是因为您在同一文件下保存了两个公共类(枚举也是类)。
创建两个单独的文件并将枚举写入一个,将其另存为Day.java
。以及class EnumTest
的其他文件,并将其另存为EnumTest.java
别忘了把它们放在同一个包装下面。否则你将不得不用import packagename.Day
或
更简单的方法,从枚举中删除public
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
现在你的代码将编译
答案 1 :(得分:2)
通常所有public
类/枚举/接口都分别在一个文件中定义(所以Day.java,EnumTest.java等)。
但是,除非从外部访问,否则您不必创建课程/枚举/界面public
:
enum Day { ... }
public class EnumTest {
Day day;
...