CS 231 Lab 2

2D Arrays

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

Here are the links to the API's for the most recent versions of Java:


  1. Create a working directory for today's lab. Then start a Java file called Grid.java and make a public class called Grid.
  2. 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

  3. 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 )

  4. 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 references and column references 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 [Hint: the expression 'a' means the ascii value of the character 'a'.].

  5. 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 are comfortable with the above tasks, go on to the project.