package com.hanqi; public class Car { // 品牌 private String pinP; // 读 public String getPinP() { return pinP; } // 写 public void setPinP(String pinP) { System.out.println("车设置为" + pinP); this.pinP = pinP; } // 状态 private String zhuangT = "静止"; public String getZhuangT() { return zhuangT; } // 油量 private double youL = 0; public double getYouL() { return youL; } // 邮箱 private double youX; public double getYouX() { return youX; } public void setYouX(double youX) { this.youX = youX; } // 一次加满,方法的重载 public void jiayou() { System.out.println("一次性加满"); double yjyl = this.youX - this.youL; jiayou(yjyl); } // 加油 public void jiayou(double youL) { // 油箱容量大于0 if (youX <= 0) { System.out.println("忘装油箱了"); return;// 不需要返回值,停止运行,返回上一级。 } // 加油量大于0 else if (youL < 0) { System.out.println("不要偷我的油"); return; } // 只有静止状态才能加 else if (!zhuangT.equals("静止")) { System.out.println("请熄火,再加油"); return; } // 不能超过油箱容量 else if (this.youL + youL > this.youX) { System.out.println("油箱已经加满,不要在加了"); double syyl = this.youL; this.youL = this.youX; System.out.println("这次加了" + (this.youX - syyl) + "升油"); } // 剩余油量不能小于0 else { this.youL += youL; System.out.println("这次加了" + youL + "升油"); } } public void faDong() { if (this.getYouL() <= 0) { System.out.println("没有了,请先加油"); } else if (!this.getZhuangT().equals("静止")) { System.out.println("车已经发动"); } else { this.zhuangT = "发动"; System.out.println("车发动了"); } } private double zongLC; public double getZongLC() { return zongLC; } // 行驶 public void xingS(double lic, double youh) { // 车的状态是发动 if (!this.getZhuangT().equals("发动")) { System.out.println("请发动汽车"); } else { // 行驶 // double zyh = lic*youh/100; double lc = this.youL * 100 / youh; if (lc < lic) { System.out.println("最多行驶" + lc + "公里"); this.zongLC += lc; this.youL = 0; } else { System.out.println("行驶" + lic + "公里"); this.zongLC += lic; this.youL -= lic * youh / 100; } this.zhuangT = "静止"; } // 计算总油耗,判断是否没有油了 } /** * public Car() { System.out.println("调用了构造方法"); } */ // 构造方法重载 public Car(String pinP) { System.out.println("实例化车的品牌为" + pinP); this.pinP = pinP; } public static void main(String[] args) { // Car car = new Car(); Car car = new Car("宝马");// 默认构造方法 // car.setPinP("宝马"); car.xingS(100, 10); car.faDong(); car.setYouX(40); car.jiayou(20); System.out.println("车的品牌是" + car.getPinP() + "车的油量是" + car.getYouL() + "车的状态" + car.getZhuangT()); car.faDong(); car.xingS(300, 10); System.out.println("车的状态" + car.getZhuangT()); car.jiayou(10); System.out.println("车的油量是" + car.getYouL() + "车的状态" + car.getZhuangT()); car.jiayou(); System.out.println("车的油量是" + car.getYouL() + "车的状态" + car.getZhuangT()); } }