枚举类enum

Enum类的几个重要有用的方法

1. toString

Size.SMALL.toString(); //返回字符串"SMALL"
2. valueOf
Size s = Enum.valueOf(Size.class, "SMALL"); //将s设置为Size.SMALL

3. ordinal

Size.SMALL.ordinal(); //返回0,返回枚举常量的位置

枚举类型的工作方式

import java.util.*;

/**
 * This program demonstrates enumerated types
 */
enum Size
{
	SMALL("S"), MID("M"), LARGE("L"), EX_LG("XL");
	
	private String str;
	private Size(String data) //构造器在构造枚举常量时被调用
	{
		str = data;
	}
	
	public String getStr()
	{
		return str;
	}
}

public class Test
{
	public static void main(String args[])
	{
		Scanner in = new Scanner(System.in);
		System.out.print("enter a size: SMALL, MID, LARGE, EX_LG:  ");
		String input = in.next().toUpperCase();
		in.close();
		
		//static Enum valueOf(Class enumClass, String name)返回带指定名称的指定枚举类型的枚举常量
		Size size = Enum.valueOf(Size.class, input);
		
		System.out.println("size=" + size);
		System.out.println("str=" + size.getStr());
		if(size == Size.EX_LG)
		{
			System.out.println("good job -- you paid attention to the fat.");
		}
	}
}

output:

enter a size: SMALL, MID, LARGE, EX_LG:  small
size=SMALL
str=S
enter a size: SMALL, MID, LARGE, EX_LG:  ex_lg
size=EX_LG
str=XL
good job -- you paid attention to the fat.

你可能感兴趣的:(java)