Student Handout: Java Programming

Arrays—A Madlibs Example

 

 

A variable contains a single instance of a data type, while an array, a structure with a pre-defined number of elements in it, allows for a collection of related values. Each element is of the same type (for example, an integer, double, or String, and it has a specific position in the array known as the index. An array is basically a one-dimensional grid. As with any other variable types, an array must be declared before it can be used. You can do so using any of the following formats:

 

type[] arrayName; // only declares the array

type[] arrayName = new type[size]; // declares and constructs all at once

type[] arrayName = { val1, val2, …, lastval }; // this fills in values for arrayName

 

To illustrate, an array of days of the week could be declared in the following manner:

 

String daysOfWeek;

String[] daysOfWeek = new String[7];

String[] daysOfWeek = {“Sunday”, “Monday”, “Tuesday”, “Wednesday”,

Thursday”, “Friday”, “Saturday”};

In each of the previous examples, an array of seven Strings is created. In the second case, the array is populated as shown in the following table.

 

index

value

0

Sunday”

1

Monday”

2

Tuesday”

3

Wednesday”

4

Thursday”

5

Friday”

6

Saturday”

 

 

Each day of the week is represented as an element in the array, and it can be accessed or referred to by index. To set or use the value of one of the elements, you refer to the name of array variable and the element’s index in square brackets. In the following code, the first line sets the value of the array’s first element (index 0). The second line writes the value of the array’s fourth element (index 3).

 

daysOfWeek[0] = “Sunday”;

System.out.println(daysOfWeek[3]); // displays “Wednesday”

 

 

Once you define an array’s size, you cannot change it. You can modify the value of any element in the array, but the size is always fixed. Note this declaration:

String[] daysOfWeek = new String[7];

The array daysOfWeek has seven elements, each of which is a String The indexes start at zero and go to six. Note that there are only null (empty) values in the array at this point; the elements’ values must be set by the program. To set or use the value of one of the elements, you refer to the name of array variable and the element’s index in square brackets. In the following code, the first line sets the value of the array’s first element (index 0). The second line writes the value of the array’s fourth element (index 3).

daysOfWeek[0] = “Sunday”;

System.out.println(daysOfWeek[3]); // displays “Wednesday”

 

To experiment with arrays in a program, create a project called Madlibs and create within it a class named Madlib. Enter the following code into the Madlib class.

 

/**

* Madlib.java creates a silly, random story from arrays of words.

* @author (your name)

* @version (a version number or a date)

*

*/

public class Madlib

{

// instance variables

// array of nouns

 

private String[] nouns = {"banana", "Ferrari", "hammer", "guacamole", "bug-eyed monster"};

// array of verbs

private String[] verbs = {"eat", "drive", "whack", "transmogrify"};

/**

* Pick a noun at random from the array with a random index.

* Remember indexes start at zero.

*/

public String getNoun()

{

int size = nouns.length; // get the size of the array

int index = (int)(Math.random() * size); // random # must be < size

return nouns[index]; // send back the noun at that index

} // end of getNoun() method

/**

* Pick a verb at random from the array with a random index.

*/

public String getVerb()

{

int size = verbs.length;

int index = (int)(Math.random() * size);

return verbs[index];

} // end of getVerb() method

/**

* Generate and display the madlib.

* This is just a series of println's.

*/

public void tellStory()

{

System.out.println("Once upon a time there was a " + getNoun() + ".");

System.out.println("All it could do was " + getVerb() + " the " +

getNoun());

System.out.println("but they all " + getVerb() +

" happily ever after. The end.");

} // end of tellStory() method

/**

* Create a story from random nouns, verbs, adjectives

*/

public static void main(String[] args)

{

Madlib story1 = new Madlib(); // create a madlib object

System.out.println("Here is a story just for you\n");

story1.tellStory(); // generate and display the story

} // end of main()

} // end of Madlib class

 

YOUR JOB:

·        Add a third string array containing at least five adjectives

·        Add a getAdj()method to return a random adjective

·        Each should return a random value from the corresponding array, just as in getNoun()

·        Modify tellStory()to include adjectives

·        Add a loop so that the user can continue generating stories

EXTRAS YOU CAN ADD FOR an A:

·        Get creative and make the program better. Add more arrays and methods to allow for more variation in the story. For example, experiment with adverbs, different verb tenses, numbers, and sound effects.

·        Allow the user to enter the word lists manually.