In: Computer Science
Develop a Java program for the question below:
A running race among animals:
In a race among animals different types of animals are differenciated wih their running styles. In each iteration of the race, each participating animal makes a move acording to its style of running. Total length of the racecourt is NTotal (store this variable properly in the test class). Determine the winner animal and completion time of the race using polymorphism. Each of these animal classes extends from Animal class having a move method with no arguments. The current position of an animal is an integer atatring value is 0. In addition, each animal has a name attribute as well.
For generating random variables create an object from the Random class and invoke its randomize method with an integer argument (n).which returns an integer random number between 0 and (n-1).
Note you can generate 0.4 and 0,6 proababilities with the randomize method. Invoke the method with an argument of 5 if 0 or 1 comes the rabit sleapes at this iteration, if 2,3 or 4 comes, the rabit makes a move.
import java.util.Random;
class Animal {
String name;
int position, score;
public Animal(String name) {
this.name = name;
this.position = 0;
this.score = 0;
}
void move() {
this.score++;
}
}
class Rabbit extends Animal {
public Rabbit(String name) {
super(name);
}
@Override
void move() {
Random random = new Random();
if (random.nextInt(5) < 2) {
this.position += 3;
}
super.move();
}
}
class Turtle extends Animal {
public Turtle(String name) {
super(name);
}
@Override
void move() {
this.position += 1;
super.move();
}
}
class Test {
public static void main(String[] args) {
int NTotal = 3;
Animal[] animals = new Animal[4];
animals[0] = new Rabbit("harry");
animals[1] = new Rabbit("jason");
animals[2] = new Turtle("alpha");
animals[3] = new Turtle("thor");
loop:
while (true) {
for (int i = 0; i < animals.length; i++) {
animals[i].move();
if (animals[i].position > NTotal) {
System.out.println("Winner is " + animals[i].name + " with score " + animals[i].score);
break loop;
}
}
}
}
}