Pages

Friday, September 30, 2016

Go, Dog. Go! (Java)

// Animal Classes

abstract class Animal {
  String name;
  double multiplier;
  Animal(String name, double percentAbility) {
    this.name = name;
    this.multiplier = percentAbility / 100;    
  }
  abstract double typicalTopSpeed();
  abstract String typeOfAnimal();
  double topSpeed() {
    return this.multiplier * typicalTopSpeed();
  }
}

class Greyhound extends Animal {
  Greyhound(String name, double percentAbility) {
    super(name, percentAbility);
  }
  String typeOfAnimal() {
    return "greyhound";
  }
  double typicalTopSpeed() {
    return 43;
  }
}

class Ostrich extends Animal {
  Ostrich(String name, double percentAbility) {
    super(name, percentAbility);
  }
  String typeOfAnimal() {
    return "ostrich";
  }
  double typicalTopSpeed() {
    return 40;
  }
}

// Race Class

class Race {
  Animal runner1;
  Animal runner2;
  Race(Animal animal1, Animal animal2) {
    this.runner1 = animal1;
    this.runner2 = animal2;
  }
  String whoLoses() {
    if (this.runner1.topSpeed() > this.runner2.topSpeed()) {
      return runner2.name;
    }
    else if (this.runner2.topSpeed() > this.runner1.topSpeed()) {
      return runner1.name;
    }
    else {
      return "neither";
    }
  }
  String results() {
    String results = "In a race between ";
    results += this.runner1.name;
    results += " the " + this.runner1.typeOfAnimal();
    results += " and " + this.runner2.name;
    results += " the " + this.runner2.typeOfAnimal();
    results += ", " + this.whoLoses();
    results += " loses.";
    return results;
  }
}

// Main Method Class

class GoDogGo {
  static void go() {
    Greyhound grit = new Greyhound("Grit", 110);
    Ostrich oliver = new Ostrich("Oliver", 120);
    Race race = new Race(grit, oliver);
    System.out.print(race.results());
  }
  public static void main(String[] args) {
    GoDogGo.go();
  }
}