Advertisement
mmayoub

classes, Car class, Exercise 02 slide 47

Jul 7th, 2017
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. package class170706;
  2.  
  3. public class Car {
  4.     // min number of digits in a valid car number
  5.     private final int MIN_DIGITS_NO = 7;
  6.     // max number of digits in a valid car number
  7.     private final int MAX_DIGITS_NO = 8;
  8.  
  9.     // properties
  10.     private int carNumber; // number of digits in the valid range
  11.     private int speed; // positive for forward, negative for reverse
  12.  
  13.     // return car number
  14.     public int getCarNumber() {
  15.         return this.carNumber;
  16.     }
  17.  
  18.     // set car Number
  19.     public boolean setCarNumber(int carNumber) {
  20.         // if argument is invalid
  21.         if (!isValidNumber(carNumber)) {
  22.             // do nothing and return false
  23.             return false;
  24.         }
  25.         this.carNumber = carNumber;
  26.         return true;
  27.     }
  28.  
  29.     // check if carNumber is valid
  30.     // return true if valid, false otherwise
  31.     private boolean isValidNumber(int carNumber) {
  32.         // valid number as defined by MIN_DIGITS_NO and MAX_DIGITS_NO
  33.         int digitCount= (int)(Math.log10(carNumber)+1);
  34.         return (digitCount >= MIN_DIGITS_NO & digitCount <= MAX_DIGITS_NO);
  35.     }
  36.  
  37.     // return speed
  38.     public int getSpeed() {
  39.         return this.speed;
  40.     }
  41.  
  42.     // accelerate: increase speed by 1, at the current direction
  43.     public void accelerate() {
  44.         this.speed += this.speed >= 0 ? 1 : -1;
  45.     }
  46.  
  47.     // decelerate: decrease speed by 1
  48.     // negative number indicate driving in reverse
  49.     public void decelerate() {
  50.         this.speed -= this.speed >= 0 ? 1 : -1;
  51.     }
  52.  
  53.     // stop the car
  54.     public void stop() {
  55.         this.speed = 0;
  56.     }
  57.  
  58.     @Override
  59.     public String toString() {
  60.         return String.format("[carNumber=%d, speed=%d]", this.carNumber,
  61.                 this.speed);
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement