Two Dimensional Arrays in Java

Previously, we covered how to use arrays in Java. If you are unfamiliar with arrays, please read through the first tutorial on arrays here. Two dimensional arrays are used to hold numbers that correspond to one another. One dimensional arrays can be thought of as a collection of variables listed in an indefinite number of rows, but a single column. Two dimensional arrays allow for both indefinite rows and columns. Values stored in columns may correspond to values adjacent to them. For example, two dimensional arrays may be used to take record samples taken from a population. The far left column could hold the person's name, next could hold their sex, then height, weight, and so on. Two dimensional arrays are declared similarly to one dimensional arrays, as follows: int[][] list = new int[5][5]; This creates a 5x5 integer array, called list. However, this would limit us to only holding integer values. If you want an array that holds numbers and words, you would have to use a string array. String[][] list = new String[5][2]; For this example, I made a two dimensional string array that has five rows, and two columns. We can now populate the array by specifying which row and column you wish to edit. Remember that the rows begin with row 0, not row 1. Same goes for columns.
  1. public class twodimensions
  2. {
  3.  
  4. public static void main(String[] args)
  5. {
  6.  
  7. String[][] array = new String[5][2]; //creates array with 5 rows and 2 columns
  8.  
  9. array[0][0] = "Michael";
  10. array[1][0] = "Jyoti";
  11. array[2][0] = "Mario";
  12. array[3][0] = "Sakura";
  13. array[4][0] = "Maribeth";
  14.  
  15. array[0][1] = "30";
  16. array[1][1] = "24";
  17. array[2][1] = "41";
  18. array[3][1] = "17";
  19. array[4][1] = "55";
  20.  
  21. System.out.println("\n" + array[0][0] + "'s age is " + array[0][1] + ".");
  22. System.out.println("\n" + array[1][0] + "'s age is " + array[1][1] + ".");
  23. System.out.println("\n" + array[2][0] + "'s age is " + array[2][1] + ".");
  24. System.out.println("\n" + array[3][0] + "'s age is " + array[3][1] + ".");
  25. System.out.println("\n" + array[4][0] + "'s age is " + array[4][1] + ".\n");
  26.  
  27. }
  28. }</java
  29.  
  30. This is a basic example of a program that uses two dimensional arrays to store names and ages. They are all displayed to the user at the very bottom. As an exercise, try adding functionality so that the user inputs the ages themselves. Hint: You don't need to set initial values for the array containers that are going to be given values by the user's input.

Tags

Add new comment