java学习笔记-枚举类

    xiaoxiao2021-03-25  31

    枚举法本质其实就是一个类

    一、常量的使用

    public classenumeration {

       public enum color {

          red,black,green;

       }

       public static voidmain(String[] args) {

          showColor(color.red);

       }

       static voidshowColor(color color){

          switch(color){

          case red:System.out.println(color);break;

          case black:System.out.println(color);break;

          case green:System.out.println(color);break;

          }

       }

    }

    color.red返回red这个值

     

    二、自定义函数

    public class enumeration1 {

        public enum commodity{

           电风扇(1,124.23),洗衣机(2,4500.0),电视机(3,8800.9),冰箱  (4,5000.88),空调机(5,4456.0);

           private int index;

           private double price;

           private commodity(int index,double price){       //枚举法的构造函数必须用private修饰

               this.index=index;

               this.price=price;

           }

           public int getIndex(){

               return index;

           }

           public double getPrice(){

               return price;

           }

        }

       

        public static void main(String[] args) {

           commoditya[]=commodity.values();      //返回的是一个字符串数组

           System.out.println("*********欢迎进入商品批发城********");

           System.out.println("编号     商品      价格");

           for(commodity b:a){

               System.out.println(b.getIndex()+"    "+b+"    "+b.getPrice());

           }

           System.out.println("请输入你批发的商品编号:");

           Scannersc=new Scanner(System.in);

           int num=sc.nextInt();

           System.out.println("请输入批发数量:");

           int num2=sc.nextInt();

           if(num>5){

               System.out.println("请输入正确的商品编号");

           }else {

               for (int i = 0; i < a.length; i++) {

                  if(a[i].getIndex()==num){

                      System.out.println("您需要付款:"+a[i].getPrice()*num2);

                  }

               }

           }

        }

    }

    枚举法本质就是类,它的构造方法必须用private修饰并且构造的方法没有返回值,被private修饰的变量通过被修饰为public的方法访问或返回。

    enum.values() 返回元素的集合。

     

    自定义变量其实就用到了封装,将变量和构造函数设置为私有,外部类通过调用set方法和get方法来设置变量值和获取变量值。

     

    转载请注明原文地址: https://ju.6miu.com/read-150232.html

    最新回复(0)