In this exercise I need to extend DecrementingCarousel. I need to implement HalvingCarousel. This subclass must halve elements instead of decrementing it by one. Note that you need to apply regular integer division, discarding the remainder. For example, 5 / 2 = 2.
I have a superclass called DecrementCarousel which has a method that returns an object called CarouselRun. CarouselRun has its own methods which I need to override in HalvingCarousel, but I don't know how.
Decrement Carousel:
<pre>public class DecrementingCarousel {
private final int capacity;
static int[] carousel;
int index;
boolean isRun;
{
index = 0;
isRun = false;
}
public DecrementingCarousel(int capacity) {
this.capacity = capacity;
carousel = new int[capacity];
}
public boolean addElement(int element){
if (element > 0 && index < capacity && !isRun) {
carousel[index++] = element;
return true;
}
return false;
}
public CarouselRun run() {
if (!isRun) {
isRun = true;
return new CarouselRun();
}
return null;
}
}
Here are methods in CarouselRun:
<pre>public class CarouselRun {
protected final int[] array = DecrementingCarousel.carousel.clone();
protected int position = 0;
public int next() {
if (isFinished())
return -1;
else {
while (array[position %= array.length] <= 0) {
position++;
}
}
return array[position++]--;
}
public boolean isFinished() {
for (int el : array)
if (el > 0)
return false;
return true;
}
}
This is HalvingCarousel class:
public class HalvingCarousel extends DecrementingCarousel {
public HalvingCarousel(final int capacity) {
super(capacity);
}
}
Main Class:
public class Main {
public static void main(String[] args) {
CarouselRun run = new HalvingCarousel(7).run();
System.out.println(run.isFinished());
System.out.println(run.next());
DecrementingCarousel carousel = new HalvingCarousel(7);
carousel.addElement(20);
carousel.addElement(30);
carousel.addElement(10);
System.out.println(run.isFinished());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.next());
System.out.println(run.isFinished());
System.out.println(run.next());
}
}
What I have tried:
I tried to override the methods from Decrementing Carousel in HalvingCarousel and then to make another class called HalvingCarouselRun where I could called methods from CarouselRun. I'm not sure about this part, how to make the elements to halve