This program will simulate the growth and decrease of bugs based on breeding the
ID: 3701360 • Letter: T
Question
This program will simulate the growth and decrease of bugs based on breeding the bugs and spraying the bugs.
a. Create a Bug class
b. Create an instance variable to hold the number of bugs.
c. Create a constructor that sets the original number of bugs to an amount that is provided through the argument. Hint: BankAccount with an initial balance.
d. Create a method call breedBugs. This method will not return anything and will not have an argument. The breedBugs method should double the number of bugs each time it is invoked or called
e. Create a method called sprayBugs. This method will not return anything and will not have an argument. The sprayBugs should decrease the number of bugs by 1/4 each time it is invoked. Multiply the total bugs by .75. Your bugs should be integers because you do not have partial bugs. However, because we are dividing your result may be a double. To take care of this problem, put (int)(your formula) in your method. This is a cast. Be sure and put your formula in ().
f. Create a method to return the number of bugs.
g. Create a BugTester class
h. Create a main
i. Create a Bug object and begin with 10 bugs. Hint: Remember how you created a BankAccount Object with an initial balance.
j. Call / invoke the breedBugs method . Hint: Call deposit but no parameters.
k. Call the sprayBugs method 3 .
l. Print the number of bugs (The result should be an integer – no half dead bugs)
m. Repeat j – l two additional times. This means that you will breed, spray and print 3 times.
Explanation / Answer
import java.util.*;
class Bug
{
private int numBugs;
public Bug()//default constructor
{
numBugs = 0;
}
public Bug(int numBugs)//argument constructor
{
this.numBugs = numBugs;
}
public int getBugs()
{
return numBugs;
}
public void setBugs(int numBugs)
{
this.numBugs = numBugs;
}
public void breedBugs()
{
numBugs= numBugs * 2; // double the bugs
}
public void sprayBugs()
{
numBugs = (int)(numBugs*0.75); // decrease the bugs by 1/4
}
}
class BugTester
{
public static void main (String[] args)
{
Bug b = new Bug(10);
for(int i = 1;i<=3;i++)
{
//breed bugs
b.breedBugs();
//spray bugs
b.sprayBugs();
// display bugs left
System.out.println("Number of bugs after breeding and spraying "+ i+ " time : "+b.getBugs());
}
}
}
Output:
Number of bugs after breeding and spraying 1 time : 15
Number of bugs after breeding and spraying 2 time : 22
Number of bugs after breeding and spraying 3 time : 33
Do ask if any doubt. Please upvote.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.