枚举类型一些方法的用法:
package learn;
import java.util.*;
//输入:EXTRA_LARge
//输出:
//EXTRA_LARGE
//abbreviation=XL
//Good job--you paid attention to the _.
public class Test {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter a size:(SMALL,MEDIUM,LARGE,EXTRA_LARGE)");
String input=in.next().toUpperCase();//都转为大写
Size size=Enum.valueOf(Size.class,input);//得到对应枚举常量
System.out.println(size);
System.out.println("abbreviation="+size.getAbbreviation());
if(size==Size.EXTRA_LARGE){
System.out.println("Good job--you paid attention to the _.");
}
}
enum Size{
SMALL("S"),MEDIUN("M"),LARGE("L"),EXTRA_LARGE("XL");
//如果需要的话,可以为枚举类型增加构造器、方法和字段
private String abbreviation;
private Size(String abbreviation) {//构造方法私有
this.abbreviation=abbreviation;
}
public String getAbbreviation(){
return abbreviation;
}
}//枚举类型其实是一个类,此枚举类刚好有4个实例:SMALL,MEDIUN,LARGE,EXTRA_LARGE,S、M、L、XL即为这些实例传入的参数
}