介绍汽车的部件---------------汽车的发动机Engine描述如下:
- 颜色
- 重量
- 有两种状态on,off,
- 可以点燃turnon,熄灭turnoff,点燃时状态为on,熄灭时状态为off车轮Wheel描述如下:
- 颜色
- 半径(m)
- 有两种状态,转动turn,静止stop--------------------------------
现在有汽车Car的描述:
- 颜色
- 有1个发动机
- 有4个车轮
- 有两种状态,行驶状态move和停止状态stop;
- 汽车可以开动poweron,开动时,发动机点燃使发动机状态为on,发动机点燃使4个轮子转动,4个轮子转动使汽车行驶move
- 汽车可以停止poweroff,停止时发动机熄火为off,发动机off则时轮子停转stop,轮子停转使汽车停下来stop.难点:
1.汽车中部件数量的描述
2.通过对汽车的操作,使其内部部件状态改变,最终改变汽车的状态.这样一个类,怎样设计使其实现呢? ^_^~,听说<thinking in java 2>里有类似的例程,可否具体指明出处?

解决方案 »

  1.   

    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();
      }}
      

  2.   

    to bruceAlex(书健) ( ) 
    -----------------------------
    不好意思,还想问一句<thinking in java 2>里有类似的例程,可否具体指明出处?