设计⼀个共享单车Bike类

设计⼀个共享单车Bike类

要求

  • 有接受⼀个编号(long类型)作为参数的构造函数
  • 私有变量: 借出状态boolean borrowed, ⻋辆编号final long id, 车胎⽓体剩余量
    • 变量须有对应的get和set⽅法
  • 类成员⽅法: borrowBike() 借车 returnBike() 还⻋ pump() 给⻋打⽓
    • 注意: 如果该⻋被重复借⼊或者重复归还都要阻⽌这个操作并输出错误信息; 车辆每次被借出,车胎⽓体剩余量就会-1, ⻋胎没⽓时需要打⽓才能借出
  • 写⼀个静态(static)⽅法 printInfo(Bike bike)打印该⻋的id和状态
    • (也可以重写类成员⽅法toString()来达到同样的⽬的)
  • 最后写⼀个main函数测试⼀下上述功能是否正常

测试代码如下:

package 测试代码;

public class Bike {
  private boolean borrowed; //借出状态
  private final long id; //⻋辆编号
  private int tireGas; //车胎⽓体剩余量

  public Bike(long id) { //接受⼀个编号(long类型)作为参数的构造函数
      this.id = id;
      this.setTireGas(3); //设置初始轮胎气体为3
  }

  public boolean getBorrowed() {
      return borrowed;
  }

  public void setBorrowed(boolean borrowed) {
      this.borrowed = borrowed;
  }

  public long getId() {
      return id;
  }

  public int getTireGas() {
      return tireGas;
  }

  public void setTireGas(int tireGas) {
      this.tireGas = tireGas;
  }

  void borrowBike() { //借车
      if(this.getTireGas()>0) {
          if (!this.getBorrowed()) {
              this.setBorrowed(true);
              this.setTireGas(this.getTireGas()-1);
              System.out.println("借车成功");
          } else {
              System.out.println("车辆已被借出,无法再次借出");
          }
      } else {
          System.out.println("车胎没气了,请充满气后再借");
      }
  }

  void returnBike() { //还⻋
      if(this.getBorrowed()) {
          this.setBorrowed(false);
          System.out.println("还车成功");
      } else {
          System.out.println("车辆还未被借出,无法归还");
      }
  }

  void pump() { //给车打⽓
      if(this.getTireGas() == 3) {
          System.out.println("当前无需打气");
      } else {
          this.setTireGas(3);
          System.out.println("车胎已充满");
      }
  }

  @Override
  public String toString() { //重写toString()方法来打印该⻋的id和状态
      return "该车的编号为:" + this.id +
              "号,当前状态:" + (this.getBorrowed() ? "已被借出" : "未被借出");
  }
}

class Test {
  static void printInfo(Bike bike) { //通过静态(static)⽅法 printInfo(Bike bike)来打印该⻋的id和状态
      System.out.println("该车的编号为:" + bike.getId() +
              "号,当前状态:" + (bike.getBorrowed() ? "已被借出" : "未被借出"));
  }

  public static void main(String[] args) { //测试功能
      Bike bike = new Bike(0406);
      System.out.println(bike.getBorrowed());
      System.out.println(bike.toString());
      bike.borrowBike();
      bike.borrowBike();
      bike.returnBike();
      bike.borrowBike();
      bike.returnBike();
      bike.borrowBike();
      bike.returnBike();
      bike.borrowBike();
      System.out.println(bike.toString());
      bike.pump();
      bike.pump();
      bike.returnBike();
      printInfo(bike);
  }
}

运行结果如下:

posted @ 2022-02-05 22:37  中国移不动~~~  阅读(101)  评论(0)    收藏  举报