一个关于枚举类型的程序
import java.util.*;
enum Size
{
SMALL("S"),MEDIUM("M"),LARGE("L"),EXTRA_LARGE("XL");
private Size(String abbreviation){this.abbreviation=abbreviation;}
public String getAbbreviation(){return abbreviation;}
private String abbreviation;
}
public class EnumTest
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a size:");
String input=in.next().toUpperCase();
Size size=Enum.valueOf(Size.class,input);
System.out.println("size="+size);
System.out.println("abbreviation="+size.getAbbreviation());
if(size==Size.EXTRA_LARGE)
System.out.println("Good job--you paid attention to the_.");
}
}
问题如下:
//假如我输入的是字符串"SMALL",那么这里的abbreviation变量什么时候变成"S"了呢?
还有private Size(String abbreviation){this.abbreviation=abbreviation;}这个函数又在哪个地方调用了呢?
------解决方案--------------------abbreviation变量没初始化。
------解决方案--------------------SMALL("S"),MEDIUM("M"),LARGE("L"),EXTRA_LARGE("XL");
这四个实例的private String abbreviation就是它们括号里的那个字符串阿