Java中枚举类型的问题
我对 Java 编程非常陌生,在使枚举类型工作时遇到一些问题。在我的程序中,我声明了以下静态变量:
class Employee {
enum Gender {MALE, FEMALE};
static final double NORMAL_WORK_WEEK = 37.5;
static int numberOfFemales;
static int numberOfMales;
Gender sex;
}
我添加了一个用于打印相关信息的方法,以及以下方法:
static void registerEmployeeGender(Gender sex) {
switch(sex) {
case MALE:
numberOfMales++; break;
case FEMALE:
numberOfFemales++; break;}
}
在我尝试运行程序的客户端中,我无法使用最后一个方法。假设我创建一个对象 Employee1,然后输入:
Employee1.registerEmployeeGender(FEMALE);
然后我收到错误消息: FEMALE 无法解析为变量。
是什么原因导致此错误消息?就像我说的,我对 Java 还很陌生,这是我第一次尝试使用枚举类型,所以我可能做错了一些事情。如果有人能给我任何帮助,我将不胜感激。
当然,我在这里只发布了程序的一部分,但这是唯一给我一条错误消息的部分。如果您需要我发布该程序的更多内容或全部内容,请告诉我。
预先感谢您的任何帮助!
I am very new to Java-programming, and have some problems in getting an enumerated type to work. In my program I have declared the following static variables:
class Employee {
enum Gender {MALE, FEMALE};
static final double NORMAL_WORK_WEEK = 37.5;
static int numberOfFemales;
static int numberOfMales;
Gender sex;
}
I have added a method for printing relevant information, as well as the following method:
static void registerEmployeeGender(Gender sex) {
switch(sex) {
case MALE:
numberOfMales++; break;
case FEMALE:
numberOfFemales++; break;}
}
In my client where I attemt to run the program, I am unable to use this last method. Say I create an object, Employee1, and type:
Employee1.registerEmployeeGender(FEMALE);
I then get the error message: FEMALE cannot be resolved to a variable.
What is causing this error message? Like I said, I am quite new to Java, and this is my first attempt at using the enumerated type, so I probably have done something wrong. If anyone can give me any help, I would greatly appreciate it.
Of course, I have only posted part of the program here, but this is the only part that is giving me an error message. If you need me to post more of the program, or all of it for that matter, please let me know.
Thanks in advance for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
并确保在代码中添加以下导入语句
use
and make sure that u make the following import statement in your code
您需要
静态导入
枚举值,以便能够按照您提供的方式静态使用它们:但是,通常的做法是仅导入枚举
并指定枚举名称:
You need to
static import
the enum values in order to be able to use them statically the way as you presented:The normal practice, however, is to just import the enum
and specify the enum name as well:
要访问枚举项,请像这样使用“Gender.FEMALE”
This 可能对您有更多帮助。
To access the enum items use it like this "Gender.FEMALE"
This might help you more.