Let’s redo the previous program for handling two liquid containers. This time we’ll create a class “Container”, which is responsible for managing the contents of a container.
My Code
LiquidContainers2
import java.util.Scanner;
public class LiquidContainers2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Container firstCont = new Container();
Container secondCont = new Container();
while (true) {
//print results
System.out.println("First: "+ firstCont);
System.out.println("Second: " + secondCont);
String input = scan.nextLine();
if (input.equals("quit")) {
break;
}
String[] parts = input.split(" ");
String command = parts[0];
int amount = Integer.valueOf(parts[1]);
if (amount > 0) {
//add command
if (command.contentEquals("add")) {
firstCont.add(amount);
}
//move command for firstCont
if (command.contentEquals("move")) {
if(firstCont.contains() > amount){
secondCont.add(amount);
} else {
secondCont.add(firstCont.contains());
}
firstCont.remove(amount);
}
//remove command for secondCont
if (command.contentEquals("remove")) {
secondCont.remove(amount);
}
}
}
}
}
Container
public class Container {
private int amount;
public Container() {
this.amount = 0;
}
public int contains() {
return this.amount;
}
public void add(int amount) {
if (amount > 0) {
this.amount += amount;
}
if (this.amount > 100) {
this.amount = 100;
}
}
public void remove(int amount) {
if (amount > 0) {
this.amount -= amount;
}
if (this.amount < 0) {
this.amount = 0;
}
}
public String toString(){
return this.amount + "/100";
}
}
Model Code
LiquidContainers2
import java.util.Scanner;
public class LiquidContainers2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Container first = new Container();
Container second = new Container();
while (true) {
System.out.println("First: " + first);
System.out.println("Second: " + second);
System.out.print("> ");
String input = scan.nextLine();
if (input.equals("quit")) {
break;
}
String[] partsOfInput = input.split(" ");
input = partsOfInput[0];
int amount = Integer.valueOf(partsOfInput[1]);
if (input.equals("add")) {
first.add(amount);
}
if (input.equals("move")) {
if (amount > first.contains()) {
amount = first.contains();
}
first.remove(amount);
second.add(amount);
}
if (input.equals("remove")) {
second.remove(amount);
}
System.out.println("");
}
}
}
Container
public class Container {
private int contains;
public Container() {
this.contains = 0;
}
public void add(int amount) {
if (amount < 0) {
return;
}
this.contains = this.contains + amount;
if (this.contains > 100) {
this.contains = 100;
}
}
public void remove(int amount) {
if (amount < 0) {
return;
}
this.contains = this.contains - amount;
if (this.contains < 0) {
this.contains = 0;
}
}
public int contains() {
return this.contains;
}
@Override
public String toString() {
return "" + this.contains + "/100";
}
}
Comments
None