Arrays Lab

Work with a random number generator to explore arrays, iteration, and decision making.

Background

Two 'D6's, six-sided dice

You will write today’s program from scratch. Create a new Java class named ArrayPlay with a main method. For each step below, you should add code to the program without replacing prior code. When you are finished, this program will provide you with a reference for working with arrays including initializing, printing, and comparing. This lab involves formatting Strings. If you haven’t completed the (Horstmann) Chapter 4 reading (especially 4.3.2), consider skimming it. You may also find the JDK documentation of the Formatter class (especially the Format String Syntax section) useful. Dr. Mayfield (et al.)’s ThinkJava2 available free online is also a handy supplemental resource (see e.g. its 3.5 Formatting Output , and consider learning this search engine operator since this version of the book doesn’t seem to provide a search mechanism).

Objectives

  1. Use an array to store a sequence of values.
  2. Display the contents of an array with a loop.
  3. Practice manipulating various types of arrays.
  4. Write methods using array parameters.

Key Terms

Array Initializer
list of values used to instantiate and initialize an array in one step (see more on Array Creation Expressions vs. Array Initializers, if you're curious actually those both go to higher dimensional arrays which is out of scope for this activity. Probably skimming ThinkJava2's Creating Arrays is a sufficient quick reference)
array.length
read-only attribute of an array that stores the number of elements
subscript (also "index")
integer value in brackets [ ] that specifies an element of an array
ArrayIndexOutOfBoundsException
error raised when trying to access a[i] where i < 0 or i >= a.length

Part 1: Sequentially accessing an array

Whenever you are asked to do something to your array and then print it, you should finish the update step first and then have a separate loop to do the printing.

  1. In the main method, create a single array of integers that is 6 elements long.
  2. Initialize each of the array elements to the value -1 using a loop of your choice.
  3. In another loop, print each element of the array with messages that look like:
    • array[0] = -1
      array[1] = -1
      ...
      
  4. Add code to change the value of each element of the array to its subscript. For example, array[3] should hold the value 3.
  5. Print the new contents of the array with the same message format as step 3. (You may copy and paste the code from step 3. Your program should now print both versions of the array.)
  6. add code to re-initialize your array contents to all zeros.
  7. Print the string Array Play (on its own line) to conclude Part 1.

Part 2: Randomly accessing an array

  1. Download Die.class for use in this Part and later. Assuming you created the Prerequisite File Hierarchy, you should then:
    1. Create a new directory (call it something about this activity, e.g. lab04) in the provided directory.
    2. move the Die.class file you downloaded into the newly directory.
    3. In Eclipse, right-click on the the current Java Project you’re using, and choose Properties... (last entry in the context menu).
    4. in the left pane, select Java Build Path.
    5. in the right pane, select the tab, labeled Libraries.
    6. click the Classpath item in the center pane.
    7. click the button no the far right, labeled Add External Class Folder....
    8. navigate to the provided directory and select the lab04 directory.
    9. Click Apply and Close.
  2. Create a new Die object.
  3. Create a loop that will iterate at least 100 times. In the loop body:
    1. Roll the die. (Don’t create a new object, just roll it again.)
    2. Based on the result of the roll, increment the corresponding cell of your array. The value of each array element should be the number of times that roll is made.
  4. After the loop finishes, print the results of the simulation. For example, if the array holds {20, 17, 19, 15, 12, 17} you would output (notice the empty line between each message):
    • 1 was rolled 20 times.
      
      2 was rolled 17 times.
      
      ...
      

Part 3: Working with multiple arrays

For this exercise, you will need two arrays of double values (I think I’ll name mine, minogue and oLeary).

  1. Use an array initializer { } to assign one of the arrays to 10 double values starting at 0.0 with each element 1.0 more than the previous (ending with the last element being set to 9.0).
  2. Instantiate the other array to store 10 elements, but do not initialize the contents yet.
  3. Print the contents of both arrays side by side on your screen, but first label this output by printing Before.
    • format the output as follows:
    • Before
      0 A1 = 0.0 A2 = 0.0
      1 A1 = 1.0 A2 = 0.0
      ...
      
  4. Copy the contents of the first array into the second, then print their contents again. Label this output After.
  5. Finally, change the element at index 0 of the first array to 99.0 and the element at index 5 of the second array to 99.0.
  6. Again, print the contents of the two arrays side by side. Label this output After Change.
  7. Check that the contents of the two arrays are indeed different. If not, make the appropriate corrections.

This is the expected output file for ArrayPlay: ArrayPlay.exp.

Part 4: Refactoring

In the lab so far, you were required to print all of the contents of an array several different times. Perhaps (as the instructions permitted) you did this by copying and pasting the same code several times. This is a bad practice. Instead, you should write a method that prints the contents of an array. This method should take the array as a parameter and print the contents of the array. You should then call this method from the appropriate places in your code.

+printArray(a: int[])

Write a (static and void) method named printArray that prints the contents of an array. The method should take the array as a parameter and print the contents of the array following the message format from Part 1. If the array is null, it should print the String null. If the array is empty, it should not print anything. You should then replace the code in your main method that prints the contents of the array with a call to this method.

+formMessage(a: int[], index: int, format: String): String

Write a static method named formMessage that defines 3 formal parameters:

  1. a is an array of integers.
  2. index is an integer that is the index of the array.
  3. format is a String that is a format string for the message. and from these parameters, returns a String that is the message for the provided array’s element at position index, with the given format. For example, if a holds {20, 17, 19, 15, 12, 17}, index is 3, and format is array[%d] = %d\n, the message would be: array[3] = 15\n. You should then replace the code in your printArray method that constructs the String to print with a call to this method. Note:
  4. you should not print anything in this method.
  5. if the provided array is null, you should return the String null.
  6. if the provided index is out of bounds, you should return the String index out of bounds.

+printArray(a: double[], b: double[])

Overload the printArray method to take two arrays of doubles as parameters. The method should print the contents of the two arrays side by side, with the first array’s elements on the left and the second array’s elements on the right. The method should print the contents of the arrays following the message format from Part 3. If either array is null, it should print the String null. If either array is empty, or if the arrays are not the same length as each other, it should not print anything. You should then replace the code in your main method that prints the contents of the arrays with a call to this method.

Submitting

Submit your final ArrayPlay.java file to Gradescope.

Acknowledgements 🙏

This lab is with thanks to at least Alvin Chao (, but likely also Nathan Sprague and David Bernstein ).