Java 中的枚舉類型採用關鍵字enum 來定義,從jdk1.5纔有的新類型,全部的枚舉類型都是繼承自Enum 類型。
package enums; import java.util.*; public class EnumTest { public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.print("enter a size:(SMALL,MEDIUM,LARGE,EXTRA_LARGE)"); String input = in.next().toUpperCase();//輸入;字符串轉換爲大寫 /** * Size.class是反射,取得Size類; * 調用構造函數,並賦值返回枚舉數組的值: * Size.SMALL;Size.MEDIUM;Size.LARGE;Size.EXTRA_LARGE */ 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"); } } enum Size{ SMALL("S"),MEDIUM("M"),LARGE("L"),EXTRA_LARGE("XL"); private String abbreviation; //定義屬性 private Size(String mabbreviation){this.abbreviation=mabbreviation;}//提供有參構造函數 public String getAbbreviation(){return abbreviation;}//獲取屬性值 }
String input = in.next().toUpperCase();//輸入;字符串轉換爲大寫
next()這個方法,你輸入了一串字符串,他只獲得空格、tab鍵、回車的第一個字符串。好比:hello world!
這個字符串,只獲得 hello
,若是是循環的話,第二次就能獲得 world!
java
nextLine()這個方法,這就是你輸入一行字符串,檢測到回車以後就保存。好比:hello world!
這個字符串,就獲得了整個hello world!
字符串。數組