![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Car { //属性 //颜色 private String yanse; //品牌 private String pinpai; //油箱容量 private double youxiangrl; //当前油量 private double dangqianyl=0; public double getDangqianyl() { return this.dangqianyl; } //加油方法 public void jiayou(double youliang) { if(youliang<0) { System.out.println("不要偷我的油"); } else if(this.dangqianyl+youliang>this.youxiangrl) { double benciyl=this.youxiangrl-this.dangqianyl; this.dangqianyl=this.youxiangrl; System.out.println("油太多了,已经加满,这次加了"+(benciyl)+"升油"); } else { this.dangqianyl+=youliang; System.out.println("这次加了"+youliang+"升油。"); } } private double xingshizlc=0; public double getXingshizlc() { return this.xingshizlc; } //行驶 public void xingshi(double xingshilc,double youhao)//百公里 { // if(this.dangqianyl<=0) { System.out.println("车没有油,怎么开?"); return; } if(xingshilc<0||youhao<0) { System.out.println("不可能这么开车"); } else{ //油耗 double dangqianyh=xingshilc*youhao/100; this.dangqianyl-=dangqianyh; //验证当前油量 this.dangqianyl=this.dangqianyl>0?this.dangqianyl:0; this.xingshizlc+=xingshilc; System.out.println("本次行驶了"+xingshilc+"公里。"); } } public String getYanse() { return yanse; } public void setYanse(String yanse) { this.yanse = yanse; } public String getPinpai() { return pinpai; } public void setPinpai(String pinpai) { this.pinpai = pinpai; } public double getYouxiangrl() { return youxiangrl; } public void setYouxiangrl(double youxiangrl) { this.youxiangrl = youxiangrl; } public Car(String pinpai, double youxiangrl) { super(); this.pinpai = pinpai; this.youxiangrl = youxiangrl; } public static void main(String[] args) { Car myBenchi=new Car("奔驰",50); System.out.println("品牌="+myBenchi.getPinpai()); System.out.println("油箱容量="+myBenchi.getYouxiangrl()); System.out.println("当前油量="+myBenchi.getDangqianyl()); myBenchi.xingshi(200, 13); myBenchi.jiayou(30); myBenchi.jiayou(30); System.out.println("当前油量="+myBenchi.getDangqianyl()); myBenchi.xingshi(300, -15); System.out.println("当前油量="+myBenchi.getDangqianyl()); myBenchi.xingshi(200, 13); System.out.println("当前总里程="+myBenchi.getXingshizlc()); System.out.println("当前油量="+myBenchi.getDangqianyl()); } }
品牌=奔驰
油箱容量=50.0
当前油量=0.0
车没有油,怎么开?
这次加了30.0升油。
油太多了,已经加满,这次加了20.0升油
当前油量=50.0
不可能这么开车
当前油量=50.0
本次行驶了200.0公里。
当前总里程=200.0
当前油量=24.0