⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 carobject.java

📁 java2 primer plus一书源程序
💻 JAVA
字号:
public class CarObject {
  public static final int COUPE = 1;
  public static final int CONVERTIBLE = 2;
  public static final int T_TOP = 3;

  public static final int V4 = 1;
  public static final int V6 = 2;
  public static final int V8 = 3;
  public static final int V10 = 4;

  private int engineType;
  private int bodyType;
  private int topSpeed;
  private int gas;
  private int oil;
  private boolean running;
  private int currentSpeed = 0;

  public CarObject()
  {
  }

  public CarObject( int engineType,
                    int bodyType,
                    int topSpeed )
  {
      this.engineType = engineType;
      this.bodyType = bodyType;
      this.topSpeed = topSpeed;
  }

  public int getEngineType()
  {
      return this.engineType;
  }

  public void setEngineType( int engineType )
  {
      if( engineType >= V4 && engineType <= V10 )
      {
          this.engineType = engineType;
      }
  }

  public int getBodyType()
  {
      return this.bodyType;
  }

  public void setBodyType( int bodyType )
  {
      if( bodyType >= COUPE && bodyType <= T_TOP )
      {
          this.bodyType = bodyType;
      }
  }

  public int getTopSpeed()
  {
      return this.topSpeed;
  }

  public void setTopSpeed( int topSpeed )
  {
      if( topSpeed > 0 )
      {
          this.topSpeed = topSpeed;
      }
  }

  public boolean isRunning()
  {
      return this.running;
  }

  public int getCurrentSpeed()
  {
      return this.currentSpeed;
  }

  public void turnOn() {
    running = true;
  }

  public void turnOff() {
    running = false;
  }

  public void accelerate() {
    switch( engineType ) {
    case V4: 
      speedUp( 2 );
      break;
    case V6: 
      speedUp( 3 );
      break;
    case V8: 
      speedUp( 4 );
      break;
    case V10: 
      speedUp( 5 );
      break;
    }
  }

  private void speedUp( int amount ) {
    if( running == false ) {
      // Do nothing - car is not running!
      return;
    }

    if( ( currentSpeed + amount ) >= topSpeed ) {
      currentSpeed = topSpeed;
    }
    else {
      currentSpeed += amount;
    }
  }

  public void decelerate() {
    if( running == false ) { 
      // Do nothing - car is not running!
      return;
    }

    if( ( currentSpeed - 5 ) <= 0 ) {
      currentSpeed = 0;
    }
    else {
      currentSpeed -= 5;
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -