JAVA常用枚举类
枚举常被用于设置常量。传统常量在实际开发过程中被定义在接口中。屁如:创建接口Constant,在Constant中定义两个常量Constant_A和Constant_B,如下:
interface Constants {// 将常量放置在接口中
public static int Constants_A = 1;
public static int Constants_B = 12;
}
由于枚举是一种数据类型,而被视为一系列具有名称的常量的集合,所以被赋予了在程序编译时检查数据类型的功能,使得用枚举定义常量逐渐取代了传统常量。使用枚举定义方法如下:
public enum Constant{
Constants_A ,
Constants_B
}
其中,enum是定义枚举类型的关键字。在程序中可以使用Constant.Constants_A来使用枚举常量。
举个例子:
试着在控制台输入要查询的星期的英文小写(屁如:mon),再输出中文对照表,表达的可能有点模糊,看代码:
import java.util.Scanner;
enum Week {
MONDAY("星期一"), TUESDAY("星期二"), WEDNESDAY("星期三"), THURSDAY("星期四"),
FRIDAY("星期五"), SATURDAY("星期六"), SUNDAY("星期日");//定义枚举常量
String week;//定义临时变量
Week(String week) {//枚举构造函数
this.week=week;
}
public String getname() {//获取枚举常量对应的值
return week;
}
public static Week getWeek(String week) {//定义一个静态方法,用来获取输入的值
switch (week) {
case "mon":
return Week.MONDAY;
case "tue":
return Week.TUESDAY;
case "wed":
return Week.WEDNESDAY;
case "thu":
return Week.THURSDAY;
case "fri":
return Week.FRIDAY;
case "sat":
return Week.SATURDAY;
case "sun":
return Week.SUNDAY;
default:
return Week.MONDAY;
}
}
}
public class EnumSetTest {
public static void main(String [] args) {
System.out.println("----------星期英汉对照表----------");
Week wkArrar[]=Week.values();//将所有枚举常量放在wkArrar[]数组中
for (Week week : wkArrar) {//使用foreach语句循环遍历并输出所有数组元素
System.out.println(week+"——"+week.getname());
}
System.out.println("请输入您要查询的星期(格式:mon):");
Scanner sc=new Scanner(System.in);
Week week=Week.getWeek(sc.next());
switch (week) {
case MONDAY:
System.out.println("MONDAY"+week.getname());//获取枚举值的中文描述
break;
case TUESDAY:
System.out.println("TUESDAY"+week.getname());
case THURSDAY:
System.out.println("THURSDAY"+week.getname());
case WEDNESDAY:
System.out.println("WEDNESDAY"+week.getname());
case FRIDAY:
System.out.println("FRIDAY"+week.getname());
case SATURDAY:
System.out.println("SATURDAY"+week.getname());
case SUNDAY:
System.out.println("SUNDAY"+week.getname());
default:
System.out.println("您的输入有误,请重新输入!");
break;
}
sc.close();//关闭输入
}
}
运行结果如下:
搞错了,再来: