首页 > 编程 > Java > 正文

java学习笔记-枚举类

2019-11-10 19:52:10
字体:
来源:转载
供稿:网友

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

一、常量的使用

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(intindex,doubleprice){       //枚举法的构造函数必须用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 (inti = 0; i < a.length; i++) {

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

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

              }

           }

       }

    }

}

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

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

 

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

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表