2D Arrays
The goal of this lab period is to practice using 2D arrays in Java.
Tasks
- Setup
Create a working directory for today's project (Project2/src/ to make it easy to submit to Gradescope). Then start a Java file called Grid.java and make a public class called Grid. Create a main function in the Grid class.
- Creating a 2-D Array
Create a 2D array of type Int. I'll call it grid.
int[][] grid;Start by allocating the 2D array in a single new statement, giving it 3 rows and 5 columns.
grid = new int[3][5];Note that the first set of square brackets corresponds to the rows of the matrix, and the second set of square brackets corresponds to the columns.
Now let's try an alternative method of creating a 2-D array by allocating the row size and column size separately:
grid = new int[3][]; for(int i = 0; i < 3; i++){ grid[i] = new int[i+3]; }Notice that by this method, the rows of
gridare actually different lengths. However, be a little careful with this method: if you try to print outgrid[0][0]between the instantiation ofgridand the start of the for loop, what happens?To fix the null entries of
grid, regardless of which way you instantiated the object, you have to go through every location in the grid and create an int to put in it. Do that now and give each location in the grid a random int (we're leaving design choices about what kind of random number up to you).+ (More Detail)
When working with 2-D arrays we often use nested for loops:
for(int i=0;i<rows;i++) { for(int j=0;j<cols;j++) { /* access the elements of the array using i and j as index variables */ } }Remember that you have to use different names for the nested loop variables. For almost all 2-D arrays, you want to loop over rows in the outer loop and columns in the inner loop. The reason is that most 2-D arrays are stored in row-major order in memory, so looping over rows and then columns accesses memory in linear order, which is faster than jumping around.
When creating a 2-D array, you have to first allocate the 2-D grid of int references, then use a nested loop, as above, to allocate each int element grid[i][j] individually. Assign to each grid[i][j] a new int by sampling a random number (you can refer back to last week for more instructions on how to do this).
- Print the Contents of the 2-D Array
If you try to print out
grid, what happens? Presumably, you'll get something likeint@somegarbage. Unfortunately, Java Arrays don't natively implement a 'pretty' toString, so you have to loop through Arrays yourself to print things out nicely. As a follow-up, if you try to print outgrid[0][0], what gets printed out?Print out the contents of the 2D array as a 2D grid using a nested for loop. Make it look nice (i.e. we don't care how you format the output as long as you and we can tell what the output means).
+ (More Detail)
If you have a 2-D array such as
int[][] grid;, you can get the number of rows by using the expressiongrid.length. You can get the number of columns of row i by usinggrid[i].length. You can use these in the for loop conditions so the code adapts to the number of rows and columns in the 2-D array, whatever size it is.The function
System.out.printdoes not put a newline character after the string to print. The functionSystem.out.println()does put a newline character. When printing the contents of a 2-D array, it's nice to keep all the elements of a row on the same line.If you want control over how Java formats numbers, especially floating point numers, look at
System.out.printfand look up printf formatting codes. - Checking if two matrices are equal
Add the following code to your main method:
int[][] arr1 = new int[2][2]; int[][] arr2 = new int[2][2]; int[][] arr3; for(int i = 0; i < 2; i++){ for(int j = 0; j < 2; j++){ arr1[i][j] = i+j; arr2[i][j] = i+j; } } arr3 = arr1;Now add 2 lines of code that check if (1) arr1 is equal to arr2, and (2) arr1 is equal to arr3 and prints the results. What do you expect the output to be? And what does it print?
Obviously, all of these arrays are the same, but Java says that the first two are not equal. This is because the==operator tests memory location rather than if the two objects are actually the same. Sincearr3was instantiated by referencingarr1's literal reference,arr1 == arr3according to Java.Your next task is to write a gridEquals method that checks whether 2 arrays contain identical values (in the same order). Your gridEquals method should determine that gridEquals(arr1, arr3) is true. It should also be the case that gridEquals( arr1, grid ) should be false (here, grid is the original random grid of numbers you created). Write both of these statements out as code tests and determine that your method passes them. Your gridEquals method should have the following declaration:
public static boolean gridEquals(int[][] arr1, int[][] arr2) - Transposing a matrix
For the next task, create a function with the following declaration:
public static int[][] transpose(int[][] arr). This function should transpose a grid. For example, transposing the grid1 2 3 4 5 6
using your method should return1 3 5 2 4 6
This method should still work even if the grid isn't a square; however, you can and should assume the grid is rectangular (i.e. all the rows have the same length).It is highly recommended that you draw a picture for this to help you guide your code. Try starting from the example above and writing out the row and column indices for each number. You should be able to use this drawing to determine how each number moves from its position in the original grid:
gridOriginal[row][column]to its position in the transposed grid:gridTransposed[rowNew][columnNew]. More specifically, how can you definerowNewandcolumnNewin terms ofrowandcolumn? You should also use your picture to determine how the size (number of rows and columns) orgridTransposedrelates to the size ofgridOriginal.At this point, your code should create a 2-D array, print it, transpose it, then print it again. You may keep other print statements, but these print statements should be clearly highlighted in your output (in whatever way you choose).
- Adding Command-line Arguments
The args parameter of the main() function contains strings from the command line. You can see this by adding code to print the elements of the args array, then running your Grid class a few different times with additional strings on the command line. For example, try both of the following ways of running Grid from the command line (after compiling Grid.java) and note how the output differs:
java Grid a b c djava Grid hello world command line argumentYour goal in this step is to add 2 command line arguments to your program that change its behavior. What those command line arguments do is up to you (surprise us!), but some ideas include using command line parameters to:
- Specify the size (number of rows and/or number of columns) of the grid
- Specify the range of random numbers to sample grid values within
- Create a boolean flag that dictates whether the grid entries should be positive or negative
- Pass in actual values for the grid instead of randomly generating them
At this point, your code should still create a 2-D array, print it, transpose it, then print it again. But some aspects of your grid (or other aspects of your program) should be controlled by 2 command line arguments supplied by the user.
- Usage Statements
Many programs you will write will require command line arguments in order to work properly. To be kind to other people using your program you should always check if the user provided enough arguments and print out a usage statement if they don't. A usage statement prints out an example of how to run the program, a description of what it does, and what the arguments mean. For example, if you type
javaon the command line with no arguments, it prints out the following.Usage: java [options][args...] (to execute a class) or java [options] -jar [args...] (to execute a jar file) or java [options] -m [/ ] [args...] java [options] --module [/ ] [args...] (to execute the main class in a module) or java [options] [args] (to execute a single source-file program) ... At the top of your main function, before any of your code runs, test if the user provided at least two command line arguments. If they did not, then print out a usage statement and return. If they did, run your program as before. Run Grid.java with no arguments, one argument, and with two or more arguments. It should print your usage statement in the first 2 cases, and run normally in the last case (i.e. generate and transpose the matrix).
- Creating a README File
Usage statements are one way to communicate with users about how to run your programs. README files are another. You should include both in all of your projects so that your project grader knows how to interact with your code! This is especially important for extensions, where you are making more design choices about how your program works. Without a README, we may not be able to replicate your results and give you credit for your work!
So how do you write a README file? There are lots of conventions for how to do this, but for our purposes, we will focus on 3 main things:
- Every project should include a file named README.txt in the main project folder (here, in Project2/)
- In that file, tell us in 1 to 3 sentences or bullet points which file(s) to run to replicate your important results.
- Tell us what command line arguments your program takes and how to use them
Lab checkpoint: Call us over and show us your README file. Have us try to run your program (don't tell us anything not in the README). Were we able to use the command line arguments correctly to run your program and have it tranpose a matrix? If so you've passed the checkpoint!
When you are done with the lab, go ahead and get started on the current project.