Entering the nth dimension with Arrays

We very briefly mentioned that an array can even hold other arrays at each position. And of course, if an array holds lots of arrays that in turn hold lots of some other type; how do we access the values in the contained arrays? And why would we ever need this anyway? Look at this next example of where multidimensional arrays can be useful.

Multidimensional Array mini app

Let's make a simple multidimensional array example. You can get the working project for this example in the download bundle. It is in the Chapter 12/Multidimensional Array Example/MainActivity.java.

Create a project with an empty Activity and call it Multidimensional Array Example. Leave the Activity name at the default it is not important.

After the call to super.onCreate… in onCreate, declare and initialize a two-dimensional array like this:

// Random object for generating question numbers
Random randInt = new Random();
// a variable to hold the random value generated
int questionNumber;

// Declare and allocate in separate stages for clarity
// but we don't have to
String[][] countriesAndCities;
// Now we have a 2-dimensional array

countriesAndCities = new String[5][2];
// 5 arrays with 2 elements each
// Perfect for 5 "What's the capital city" questions

// Now we load the questions and answers into our arrays
// You could do this with less questions to save typing
// But don't do more or you will get an exception
countriesAndCities [0][0] = "United Kingdom";
countriesAndCities [0][1] = "London";

countriesAndCities [1][0] = "USA";
countriesAndCities [1][1] = "Washington";

countriesAndCities [2][0] = "India";
countriesAndCities [2][1] = "New Delhi";

countriesAndCities [3][0] = "Brazil";
countriesAndCities [3][1] = "Brasilia";

countriesAndCities [4][0] = "Kenya";
countriesAndCities [4][1] = "Nairobi";

Now we output the contents of the array using a for loop and our Random object. Note how we ensure that although the question is random we can always pick the correct answer. Add this next code to the previous code.

/*
	Now we know that the country is stored at element 0
	The matching capital at element 1
	Here are two variables that reflect this
*/
final int COUNTRY = 0;
final int CAPITAL = 1;

// A quick for loop to ask 3 questions
for(int i = 0; i < 3; i++){
   // get a random question number between 0 and 4
   questionNumber = randInt.nextInt(5);

   // and ask the question and in this case just
   // give the answer for the sake of brevity
   Log.d("info", "The capital of "
         +countriesAndCities[questionNumber][COUNTRY]);
   
   Log.d("info", "is "
         +countriesAndCities[questionNumber][CAPITAL]);

} // end of for loop

Run the example remembering that nothing will happen on the screen as all the output will be sent to our logcat console window in Android Studio. Here is the output:

info﹕ The capital of USA
info﹕ is Washington
info﹕ The capital of India
info﹕ is New Delhi
info﹕ The capital of United Kingdom
info﹕ is London

What just happened? Let's go through this chunk by chunk so we know exactly what is going on.

We make a new object of type Random called randInt, ready to generate random numbers later in the program.

Random randInt = new Random();

We declared a simple int variable to hold a question number.

int questionNumber;

And next, we declared our array of arrays called countriesAndCities. The outer array holds arrays.

String[][] countriesAndCities;

Now we allocate space within our arrays. The first, the outer array, will now be able to hold 5 arrays and each of these 5 inner arrays will be able to hold 2 Strings each.

countriesAndCities = new String[5][2];

Now we initialize our arrays to hold countries and their corresponding capital cities. Notice with each pair of initializations the outer array number stays the same, indicating that each country/capital pair is within one inner array (a String array). And of course, each of these inner arrays is held in one element of the outer array (which holds arrays.)

countriesAndCities [0][0] = "United Kingdom";
countriesAndCities [0][1] = "London";

countriesAndCities [1][0] = "USA";
countriesAndCities [1][1] = "Washington";

countriesAndCities [2][0] = "India";
countriesAndCities [2][1] = "New Delhi";

countriesAndCities [3][0] = "Brazil";
countriesAndCities [3][1] = "Brasilia";

countriesAndCities [4][0] = "Kenya";
countriesAndCities [4][1] = "Nairobi";

To make the upcoming for loop clearer we declare and initialize int variables to represent the country and the capital from our arrays. If you glance back at the array initialization, all the countries are held in position 0 of the inner array and all the corresponding capital cities at position 1. The variables to represent this (COUNTRY and CAPITAL) are final as we will never want to change their value.

final int COUNTRY = 0;
final int CAPITAL = 1;

Now we set up a for loop to run 3 times. Note that this does not simply access the first three elements of our array it just determines the number of times we go through the loop. We could make it loop one time or a thousand times, the example would still work.

for(int i = 0; i < 3; i++){

Next, we actually determine which question to ask. Or more specifically, which element of our outer array. Remember that randInt.nextInt(5) returns a number between 0 and 4. Just what we need as we have an outer array with 5 elements also 0 through 4.

questionNumber = randInt.nextInt(5);

Now we can ask a question by outputting the Strings held in the inner array which in turn is held by the outer array that was chosen in the previous line, by the randomly generated number.

   Log.i("info", "The capital of "
         + countriesAndCities[questionNumber][COUNTRY]);

   Log.i("info", "is " 	
         + countriesAndCities[questionNumber][CAPITAL]);

}// end of for loop

For the record, we will not be using any multi-dimensional arrays in the rest of this book. So if there is still a little bit of murkiness around these arrays inside arrays then that doesn't matter. You know they exist, what they can do and you can revisit them if necessary.

Array out of bounds exceptions

An array out of bounds exception occurs when we attempt to access an element of an array that does not exist. Sometimes the compiler will catch it for us to prevent the error going into a working game. For example this:

int[] ourArray = new int[1000];
int someValue = 1; // Arbitrary value
ourArray[1000] = someValue;
// Won't compile as the compiler knows this won't work.
// Only locations 0 through 999 are valid

But what if we do something like this:

int[] ourArray = new int[1000];
int someValue = 1;// Arbitrary value
int x = 999;
if(userDoesSomething){x++; // x now equals 1000
}

ourArray[x] = someValue;
// Array out of bounds exception 
// if userDoesSomething evaluates to true! 
// This is because we end up referencing position 1000 
// when the array only has positions 0 through 999
// Compiler can't spot it. App will crash!

The only way we can avoid this problem is to know the rule. The rule that arrays start at zero and go up to their length -1. We can also use clear readable code where it is easy to evaluate what we have done and spot problems more easily.

In chapter 16 we will look at another Java topic closely related to arrays called Collections. This will take our data handling knowledge up yet another level.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.170.174