Skip to content
Snippets Groups Projects
Commit 865eb9ac authored by iliya's avatar iliya
Browse files

feat: ex3 pt2 serie2 finished

parent dd5c966f
No related branches found
No related tags found
No related merge requests found
*.class
public class Container {
private int length;
private int capacity;
public static void ensurePositiveValue(int... value) {
for (int i : value) {
if (i < 0) {
throw new RuntimeException("Value must be greater or equal to zero\tCurrently value = " + i);
}
}
}
public Container(int capacity) {
ensurePositiveValue(capacity);
this.capacity = capacity;
this.length = 0;
}
public static Container withCapacity(int capacity) {
return new Container(capacity);
}
public void fillToTheMax() {
this.length = this.capacity;
}
public void fillWith(int value) {
ensurePositiveValue(value);
if (this.length + value > this.capacity) {
throw new RuntimeException("Container overflowed");
}
this.length += value;
}
public int quantity() {
return this.length;
}
public boolean isFull() {
return this.length == this.capacity;
}
public int remaining() {
return this.capacity - this.length;
}
public void remove(int value) {
ensurePositiveValue(this.length - value);
this.length -= value;
}
public void flush() {
this.length = 0;
}
public void fillTo(Container baseContainer, Container... containers) {
int toFillBase = baseContainer.remaining();
if (toFillBase < this.length) {
baseContainer.fillWith(toFillBase);
this.remove(toFillBase);
} else {
int toFill = this.length;
this.remove(this.length);
baseContainer.fillWith(toFill);
}
for (Container container : containers) {
int toFillContainer = container.remaining();
System.out.println(this.length);
if (this.length > toFillContainer) {
container.fillWith(toFillContainer);
this.remove(toFillContainer);
} else {
int toFill = this.length;
this.remove(this.length);
container.fillWith(toFill);
}
}
}
}
public class MainContainer {
public static void main(String[] args) {
Container origin = Container.withCapacity(10);
origin.fillToTheMax();
Container destination1 = Container.withCapacity(5);
destination1.fillWith(2);
Container destination2 = Container.withCapacity(3);
Container destination3 = Container.withCapacity(10);
origin.fillTo(destination1, destination2, destination3);
assert destination1.isFull();
assert destination2.isFull();
assert destination2.remaining() == 0;
destination2.remove(2);
assert destination2.remaining() == 2;
assert !destination3.isFull();
System.out.println(destination3.quantity());
assert destination3.quantity() == 4;
destination3.flush();
assert destination3.quantity() == 0;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment