课上老师所讲实例整理:
1 package org.hanqi.pn0120; 2 3 //汽车 4 public class Car { 5 6 //颜色 7 private String yanse; 8 //品牌 9 private String pinpai; 10 //油箱容量 11 private double youxiangrl = 40; 12 //当前油量 13 private double dangqianrl; 14 15 public double getDangqianrl() 16 { 17 return this.dangqianrl; 18 } 19 //加油 20 public void jiayou(double youliang) 21 { 22 if(youliang<0) 23 { 24 System.out.println("不要偷油"); 25 } 26 else if(this.dangqianrl+youliang>this.youxiangrl) 27 { 28 //本次加油量 29 double bcyl = this.youxiangrl-this.dangqianrl; 30 this.dangqianrl=this.youxiangrl; 31 System.out.println("油太多了,已经加满了,这次加了"+bcyl+"升油"); 32 } 33 else 34 { 35 this.dangqianrl+=youliang; 36 System.out.println("这次加了 "+youliang+"升油"); 37 } 38 } 39 //private double youhao 40 private double xingshizlc = 0; 41 public double getXingshizlc() 42 { 43 return this.xingshizlc; 44 } 45 //行驶 46 public void xingshi(double xingshilc,double youhao) 47 { 48 //判断车本身有没有油 49 if(this.dangqianrl <=0) 50 { 51 System.out.println("车没有油,怎么开车"); 52 return; 53 } 54 if(xingshilc < 0 || youhao < 0) 55 { 56 System.out.println("不可能这么开车"); 57 } 58 else 59 { 60 //油耗 61 double dangqyh = xingshilc * youhao / 100; 62 this.dangqianrl -= dangqyh; 63 //验证当前油量 64 //this.dangqianrl = this.dangqianrl > 0 ?this.dangqianrl : 0; 65 if(this.dangqianrl<0) 66 { 67 this.dangqianrl=0; 68 System.out.println("你是推着车走么"); 69 } 70 this.xingshizlc += xingshilc; 71 System.out.println("本次行驶了 "+xingshilc+" 公里"); 72 } 73 } 74 75 public String getYanse() { 76 return yanse; 77 } 78 public void setYanse(String yanse) { 79 this.yanse = yanse; 80 } 81 public String getPinpai() { 82 return pinpai; 83 } 84 public void setPinpai(String pinpai) { 85 this.pinpai = pinpai; 86 } 87 public double getYouxiangrl() { 88 return youxiangrl; 89 } 90 public void setYouxiangrl(double youxiangrl) { 91 this.youxiangrl = youxiangrl; 92 } 93 94 public void setDangqianrl(double dangqianrl) { 95 this.dangqianrl = dangqianrl; 96 } 97 public Car(String pinpai, double youxiangrl) { 98 super(); 99 this.pinpai = pinpai; 100 this.youxiangrl = youxiangrl; 101 } 102 103 //main方法 104 public static void main(String[]args) 105 { 106 Car myBenchi = new Car("奔驰",50); 107 System.out.println("品牌="+myBenchi.getPinpai()); 108 System.out.println("油箱容量="+myBenchi.getYouxiangrl()); 109 myBenchi.xingshi(200, 13); 110 myBenchi.jiayou(30); 111 myBenchi.jiayou(30); 112 System.out.println("当前容量="+myBenchi.dangqianrl); 113 myBenchi.xingshi(300, 15); 114 System.out.println("当前容量="+myBenchi.dangqianrl); 115 System.out.println("当前总里程="+myBenchi.getXingshizlc()); 116 myBenchi.xingshi(200, 13); 117 System.out.println("当前总里程="+myBenchi.getXingshizlc()); 118 System.out.println("当前容量="+myBenchi.dangqianrl); 119 } 120 }
运行结果为:
思维导图: