In: Computer Science
This is to be done using JAVA
Create a Madlib bean. The bean should have several string properties and the text of the Madlib can be hardcoded. The bean should have a toString() method that outputs the text of the Madlib with the values of the properties inserted. For an additional challenge, make the text of the Madlib a property and pass an ArrayList of String arguments.
MadLib: My ______ (animal) lives in _______(place).
Following is the code for the Madlib bean. Alongside is the demo class for testing the madlib bean. Please follow the comments for understanding the code.
Output:
E:\Folder\Java>java MadlibDemo
My lion lives in den.
My sparrow lives in nest.
My snake lives in hole.
Explanation of the output:
We have provided the three animal-home pairs as this: lion-den, sparrow-nest, and snake-hole. We have set these arguments to the test of each of the madlib object. Then we have printed the output of invoking toString method on each of the madlib instances to the console.
Code:
import java.util.ArrayList;
class Madlib {
// Three properties of the madlib bean
private String animalName;
private String animalHome;
private String madlibText;
/* Method that generates the madlib text
* using an ArrayList of arguments, as
* required in the challenge.
*/
public void createMadlibText(ArrayList<String> args) {
this.animalName = args.get(0);
this.animalHome = args.get(1);
this.madlibText = "My " + this.animalName +
" lives in " + this.animalHome + ".";
}
/* The toString method that returns the
* madlib text. This has been used in
* the main method to print text to console.
*/
@Override
public String toString() {
return madlibText;
}
}
public class MadlibDemo {
public static void main(String[] args) {
// Three instances of madlib for demo
Madlib madlib1 = new Madlib();
Madlib madlib2 = new Madlib();
Madlib madlib3 = new Madlib();
// Three ArrayLists of arguments
ArrayList<String> args1 = new ArrayList<>();
args1.add("lion");
args1.add("den");
ArrayList<String> args2 = new ArrayList<>();
args2.add("sparrow");
args2.add("nest");
ArrayList<String> args3 = new ArrayList<>();
args3.add("snake");
args3.add("hole");
// Generating text for the three madlibs
madlib1.createMadlibText(args1);
madlib2.createMadlibText(args2);
madlib3.createMadlibText(args3);
// Printing text of all madlibs to console
System.out.println(madlib1.toString());
System.out.println(madlib2.toString());
System.out.println(madlib3.toString());
}
}