Car car = new Car("骑士","黑色",60);//按对应格式定义汽车的相关内荣 car.Dangqyl = 10; //引用Dangqyl 并赋值 car.Jiayou(30); //car.Youh = 20; car.Kaiche(100);
//定义属性 //品牌 public String Pinpai; //颜色 public String Yanse; //油箱容量 int Youxiangrl; //当前油量 int Dangqyl; //实例化 //构造方法 public Car(String pinpai,String yanse,int youxiangrl)//为了区分,将属性第一个字母大写,形参第一个字母小写 { Pinpai = pinpai; //this.Pinpai 指向外部的Pinpai Yanse = yanse; Youxiangrl = youxiangrl; } //加油 public void Jiayou(int Jiayl) { //实际加油量 int shijjy = Youxiangrl - Dangqyl; Dangqyl += Jiayl; if(Dangqyl >= Youxiangrl) { System.out.println("油箱已满,请停止加油!"); Dangqyl = Youxiangrl; } else { shijjy = Jiayl; } System.out.println("加油量 = " + shijjy + "当前油量为:" + Dangqyl); } //百公里油耗 public int Youh = 10; //开车 Luc 公里数 public void Kaiche(int Luc) { int You = Youh * Luc / 100; Dangqyl -= You; //没油了 if(Dangqyl <= 0) { System.out.println("没有油了,请加油后再行驶!"); } System.out.println("行驶路程 = " + You + "当前油量为:" + Dangqyl); }