In Java enum types and for, switch statement

1. enumerated type declaration

The format is:

enum sheet 举类 type name {

  Constant 1, 2 constant, the constant 3

}

Such as:

enum Number{
one,two,three,four,five    //常量
}

Note: enum interior is constant, and when the end of the set constants do not add a semicolon at the end.

2. enumerated type variable

After declaring an enumerated type, you can use this enum type declaration an enumerated type variable. It is noteworthy that enumeration constants can only take the enumerated type, "." Operator to obtain enumerated type variables by using the name and enumerated types.

The format is:

Enumerated type enumeration type variable name = name of the enumeration type name. Enumerated type constant name

Such as:

Number num1 = Number.one;

Enumerated type may be of the form:

Single 举类 type name .values ​​();

It returns an array, and the value of the enumerated type constant corresponding to the array element in turn.

Such as:

Number num[]=Number.values(); 

Then, num [0] ~ num [4] the values ​​were: one, two, three, four, five.

3. Experimental demonstration

3.1 Code

// declare enumeration type 
enum Number The { 
    One, TWO, Three, Four, Five    // constants 
} 

public  class the Test {
     public  static  void main (String [] args) { 

        Number The num1;                 // definition of an enumerated type variables 
        num1 = Number .one;             // to enumeration type variable assignment 
        System.out.println (num1); 
        
        Number the NUM [] = Number.values ();    // constants enumerated types into an array 
        for (Number the n-: NUM) { 
            of System.out.print (n- + "" ); 
        } 
        of System.out.print ( "\ n-" );

        for(Number num2:Number.values()) {  //遍历枚举类型内的常量
            switch(num2) {
            case one:
                System.out.println(num2);
                break;
            case two:
                System.out.println(num2);
                break;
            case three:
                System.out.println(num2);
                break;
            case four:
                System.out.println(num2);
                break;
            case five:
                System.out.println(num2);
                break;
            }
        }
    }
}

3.2 Experimental results

 

Guess you like

Origin www.cnblogs.com/lty1661489001/p/11588460.html