In: Computer Science
Java Coding
Background
You will create a Java class that simulates a water holding tank. The holding tank can hold volumes of water (measured in gallons) that range from 0 (empty) up to a maximum. If more than the maximum capacity is added to the holding tank, an overflow valve causes the excess to be dumped into the sewer system.
Assignment
The class will be named HoldingTank. The class attributes will consist of two int fields – current and maxCapacity. The fields must be private. The current field represents the current number of gallons of water in the tank. The maxCapacity field represents the maximum number of gallons of water that the tank can hold.
The class will contain the following methods:
Constructor – the constructor will initialize the two fields. If current is greater than maxCapacity, it will be set to maxCapacity.
Getters – there will be a getter for each field.
Setters – no setters will be defined for this class
void add(int volume) – add volume gallons to the tank. If the current volume exceeds maxCapacity, it will be set to maxCapacity.
void drain(int volume) – try to remove volume gallons from the tank. If resulting current volume is less than zero, set it to zero.
void print() – prints the current volume of the tank (in gallons)
Now create a Main class with a main method to test the HoldingTank class. Add the following code to the main method.
Example Output
The tank volume is 600 gallons
The tank volume is 850 gallons
The tank volume is 750 gallons
The tank volume is 175 gallons
HoldTank.java
class HoldTank {
private int current;
private int maxCapacity;
// constructor to initialize the values
public HoldTank(int aCurrent, int aMaxCapacity)
{
super();
current = aCurrent;
maxCapacity = aMaxCapacity;
if (current > maxCapacity)
current =
maxCapacity;
}
// setters and getters
public int getCurrent() {
return current;
}
public void setCurrent(int aCurrent) {
current = aCurrent;
}
public int getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(int aMaxCapacity)
{
maxCapacity = aMaxCapacity;
}
// adds the water to tank
void add(int n) {
current += n;
if (current > maxCapacity)
current =
maxCapacity;
}
// drains water from tank
void drain(int n) {
current -= n;
if (current < 0)
current =
0;
}
// prints current water
void print() {
System.out.println("The tank volume
is " + current + " gallons");
}
}
TestHoldTank .java
public class TestHoldTank {
public static void main(String[] args) {
HoldTank h = new HoldTank(600,
1000);
h.print();
h.add(300);
h.drain(50);
h.print();
h.add(500);
h.drain(250);
h.print();
h.drain(1200);
h.add(200);
h.drain(25);
h.print();
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me
<terminated > TestHold Tank [Java Application) C:\Soft\PegaEclipse-win64-4 The tank volume is 600 gallons The tank volume is 850 gallons The tank volume is 750 gallons The tank volume is 175 gallons