java学习笔记-枚举类

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

一、常量的使用

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方法来设置变量值和获取变量值。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值