In this implementation I must produce a carousel run, which limits number of calls to the next method. When the limit of calls reached carousel run must consider itself finished.
Carousel Run class:
<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;
}
}
Decrementing Carousel class:
<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;
}
}
DecrementingCarouselWithLimitedRun class
public class DecrementingCarouselWithLimitedRun extends DecrementingCarousel {
public DecrementingCarouselWithLimitedRun(final int capacity, final int actionLimit) {
super(capacity);
}
@Override
public CarouselRun run() {
if (!isRun) {
isRun = true;
return new DecrementingCarouselWithLimitRun();
}
return null;
}
}
DecrementingCarouselWithLimitRun class:
<pre>public class DecrementingCarouselWithLimitRun extends CarouselRun {
public int decrement = 1;
@Override
public int next() {
int beforeDecreasing;
if (isFinished())
return -1;
else {
beforeDecreasing = array[position];
array[position] -= decrement;
do {
position++;
}
while (array[position %= array.length] <= 0 && !isFinished());
}
return beforeDecreasing;
}
}
This is Main class:
public class Main {
public static void main(String[] args) {
DecrementingCarousel carousel = new DecrementingCarouselWithLimitedRun(7, 10);
carousel.addElement(20);
carousel.addElement(30);
carousel.addElement(10);
CarouselRun run = carousel.run();
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.isFinished());
System.out.println(run.next());
}
}
What I have tried:
When I'm running the code I get:
?
false
20
30
10
19
29
9
18
28
8
17
false
27
But it should be:
false
20
30
10
19
29
9
18
28
8
17
true
-1
How I stop the code to run only for a limited times?