Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170706;
- public class Car {
- // min number of digits in a valid car number
- private final int MIN_DIGITS_NO = 7;
- // max number of digits in a valid car number
- private final int MAX_DIGITS_NO = 8;
- // properties
- private int carNumber; // number of digits in the valid range
- private int speed; // positive for forward, negative for reverse
- // return car number
- public int getCarNumber() {
- return this.carNumber;
- }
- // set car Number
- public boolean setCarNumber(int carNumber) {
- // if argument is invalid
- if (!isValidNumber(carNumber)) {
- // do nothing and return false
- return false;
- }
- this.carNumber = carNumber;
- return true;
- }
- // check if carNumber is valid
- // return true if valid, false otherwise
- private boolean isValidNumber(int carNumber) {
- // valid number as defined by MIN_DIGITS_NO and MAX_DIGITS_NO
- int digitCount= (int)(Math.log10(carNumber)+1);
- return (digitCount >= MIN_DIGITS_NO & digitCount <= MAX_DIGITS_NO);
- }
- // return speed
- public int getSpeed() {
- return this.speed;
- }
- // accelerate: increase speed by 1, at the current direction
- public void accelerate() {
- this.speed += this.speed >= 0 ? 1 : -1;
- }
- // decelerate: decrease speed by 1
- // negative number indicate driving in reverse
- public void decelerate() {
- this.speed -= this.speed >= 0 ? 1 : -1;
- }
- // stop the car
- public void stop() {
- this.speed = 0;
- }
- @Override
- public String toString() {
- return String.format("[carNumber=%d, speed=%d]", this.carNumber,
- this.speed);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement