cartest.java

来自「java2 primer plus一书源程序」· Java 代码 · 共 96 行

JAVA
96
字号
public class CarTest {
  static final int COUPE = 1;
  static final int CONVERTIBLE = 2;
  static final int T_TOP = 3;

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

  static int engineType;
  static int bodyType;
  static int topSpeed;
  static int gas;
  static int oil;
  static boolean isRunning;
  static int currentSpeed;

  public static void turnOn() {
    isRunning = true;
  }

  public static void turnOff() {
    isRunning = false;
  }

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

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

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

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

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

  public static void main( String[] args ) {
    // Define the attributes of the car
    engineType = V10;
    bodyType = CONVERTIBLE; 
    topSpeed = 185;
    isRunning = false;
    currentSpeed = 0;

    // Do some things with the car
    turnOn();
    for( int i=0; i<10; i++ ) { 
      accelerate();
      System.out.println( "Current Speed: " + currentSpeed );
    }    

    for( int i=0; i<5; i++ ) { 
      decelerate();
      System.out.println( "Current Speed: " + currentSpeed );
    }
    turnOff();
  }

}

⌨️ 快捷键说明

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