CS 231: Data Structures and Algorithms (Lab Page)

Title image Lab 2
Fall 2016

2D Arrays

The goal of this lab period is to give you practice using 2D arrays.

Tasks

  1. Make a new folder for this week's project.
  2. Start a Java file called Grid.java and make a public class called Grid.
  3. Create a main function in the Grid class. The args parameter of the main function contains strings from the command line. Use a for loop to print out all of the elements of the args array. Then run your Grid class a few different times with additional strings on the command line. For example, try the following.

    $ java Grid 42 96 81 hut hut

  4. Declare two int variables in the main function, I'll call them yogi and booboo. Convert arguments 0 and 1 of the command line strings into ints and assign them to yogi and booboo. Given a string s, you can make the conversion using the Integer method parseInt().

    Integer.parseInt(s)

  5. Create a 2D array of type String. I'll call it ranger.

    String[][] ranger;

    Start by allocating the 2D array in a single new statement, giving it yogi and booboo as the row and column sizes. Then try the alternative of allocating the row size and column size separately. Is there any value in the second method?

    Allocating a 2D grid of String references does not create any String objects, however. To do that, you have to go through every location in the grid and create the String object for it. Do that now and give each location in the grid a random character.

  6. Print out the contents of the 2D array as a 2D grid using a nested for loop. Make it look nice. As part of the print process, print out the number of rows and columns in the grid, querying the array for its length.

Once you have completed the lab, go on to the project.