Storing Information with Arrays - Working with Information in New Ways - Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Sams Teach Yourself Java in 24 Hours, 7th Edition (2014)

Part III: Working with Information in New Ways

Hour 9. Storing Information with Arrays

THIS HOUR’S TO-DO LIST:

Image Create an array.

Image Set the size of an array.

Image Give a value to an array element.

Image Change the information in an array.

Image Make multidimensional arrays.

Image Sort an array.

No one benefited more from the development of the computer than Santa Claus. For centuries, humankind has put an immense burden on him to gather and process information. Old St. Nick has to keep track of the following things:

Image Naughty children

Image Nice children

Image Gift requests

Image Homes with impassable chimneys

Image Women who want more from Santa than Mrs. Claus will let him give

Image Countries that shoot unidentified aircraft first and ask questions later

Computers were a great boon to the North Pole. They are ideal for the storage, categorization, and study of information.

The most basic way that information is stored in a computer program is by putting it into a variable. So far, all variables you’ve worked with have been a single item of information, such as a floating-point number or a string.

Santa’s list of nice children is an example of a larger collection of similar information. To keep track of a list of this kind, you can use arrays.

An array is a group of related variables that share the same type. Any type of information that can be stored as a variable can become the items stored in an array. Arrays can be used to keep track of more sophisticated types of information than a single variable, but they are almost as easy to create and manipulate.

Creating Arrays

Arrays are variables grouped together under a common name. The term array should be familiar to you—think of a salesperson showing off her array of products or a game show with a dazzling array of prizes. Like variables, arrays are created by stating the type of variable being organized into the array and the name of the array. A pair of square brackets ([]) follow the type to distinguish arrays from variables.

You can create arrays for any type of information that can be stored as a variable. For example, the following statement creates an array of string variables:

String[] naughtyChild;

Here are two more examples:

int[] reindeerWeight;
boolean[] hostileAirTravelNations;


Note

Java is flexible about where the square brackets are placed when an array is being created. You can put them after the variable name instead of the variable type, as in the following:

String niceChild[];

To make arrays easier for humans to spot in your programs, you should stick to one style rather than switching back and forth. Programs that use arrays in this book always place the brackets after the variable or object type.


The previous examples create arrays, but they do not store any values in them. To do this, you can use the new keyword along with the variable type or store values in the array within { and } marks. When using new, you must specify how many different items are stored in the array. Each item in an array is called an element. The following statement creates an array and sets aside space for the values that it holds:

int[] elfSeniority = new int[250];

This example creates an array of integers called elfSeniority. The array has 250 elements that can store the months that each of Santa’s elves has been employed at the Pole. (If Santa runs a union shop, this information is extremely important to track.)

When you create an array with the new statement, you must specify the number of elements. Each element of the array is given an initial value that depends on the type of the array. All numeric arrays have the initial value 0, char arrays equal '\0', and boolean arrays have the valuefalse. A String array and all other objects are created with the initial value of null.

For arrays that are not extremely large, you can set up their initial values at the same time that you create them. The following example creates an array of strings and gives them initial values:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",
"Comet", "Cupid", "Donder", "Blitzen" };

The information that should be stored in elements of the array is placed between { and } brackets with commas separating each element. The number of elements in the array is set to the number of elements in the comma-separated list.

Array elements are numbered, beginning with 0 for the first element. A specific element can be accessed by referring to this number within [ and ] brackets. The preceding statement accomplishes the same thing as the following code:

String[] reindeerNames = new String[8];
reindeerNames[0] = "Dasher";
reindeerNames[1] = "Dancer";
reindeerNames[2] = "Prancer";
reindeerNames[3] = "Vixen";
reindeerNames[4] = "Comet";
reindeerNames[5] = "Cupid";
reindeerNames[6] = "Donder";
reindeerNames[7] = "Blitzen";

Each element of the array must be of the same type. Here, a string is used to hold each of the reindeer names.

After the array is created, you cannot make room for more elements. Even if you recall the most famous reindeer of all, you can’t add “Rudolph” as the ninth element of the reindeerNames array. The Java compiler won’t let poor Rudolph join in any reindeerNames.

Using Arrays

You use arrays in a program as you would any variable, with one difference: The element number of the array item must be provided between the square brackets next to the array’s name. You can use an array element anywhere a variable could be used. The following statements all use arrays that have already been defined in this hour’s examples:

elfSeniority[193] += 1;
niceChild[9428] = "Eli";
currentNation = 413;
if (hostileAirTravelNations[currentNation] == true) {
sendGiftByMail();
}

Because the first element of an array is numbered 0 instead of 1, this means that the highest number is one less than you might expect. Consider the following statement:

String[] topGifts = new String[10];

This statement creates an array of string variables numbered from 0 to 9. If you referred to topGifts[10] somewhere in the program, you would get an error message referring to an ArrayIndexOutOfBoundsException.

Exception is another word for error in Java programs. This exception is an “array index out of bounds” error, which means that a program tried to use an array element that doesn’t exist within its defined boundaries. You learn more about exceptions during Hour 18, “Handling Errors in a Program.”

If you want to check the upper limit of an array so you can avoid going beyond that limit, a variable called length is associated with each array that is created. The length variable is an integer that contains the number of elements an array holds. The following example creates an array and then reports its length:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer", "Vixen",
"Comet", "Cupid", "Donder", "Blitzen", "Rudolph" };
System.out.println("There are " + reindeerNames.length + " reindeer.");

In this example, the value of reindeerNames.length is 9, which means that the highest element number you can specify is 8.

You can work with text in Java as a string or an array of characters. When you’re working with strings, one useful technique is to put each character in a string into its own element of a character array. To do this, call the string’s toCharArray() method, which produces a char array with the same number of elements as the length of the string.

This hour’s first project uses both of the techniques introduced in this section. The SpaceRemover program displays a string with all space characters replaced with periods (.).

To get started, open the Java24 project in NetBeans, choose File, New File and create a new Empty Java File called SpaceRemover. Enter Listing 9.1 in the source editor and save it when you’re done.

LISTING 9.1 The Full Text of SpaceRemover.java


1: package com.java24hours;
2:
3: class SpaceRemover {
4: public static void main(String[] arguments) {
5: String mostFamous = "Rudolph the Red-Nosed Reindeer";
6: char[] mfl = mostFamous.toCharArray();
7: for (int dex = 0; dex < mfl.length; dex++) {
8: char current = mfl[dex];
9: if (current != ' ') {
10: System.out.print(current);
11: } else {
12: System.out.print('.');
13: }
14: }
15: System.out.println();
16: }
17: }


Run the program with the command Run, Run File to see the output shown in Figure 9.1.

Image

FIGURE 9.1 The output of the SpaceRemover program.

The SpaceRemover application stores the text “Rudolph the Red-Nosed Reindeer” in two places: a string called mostFamous and a char array called mfl. The array is created in Line 6 by calling the toCharArray() method of mostFamous, which fills an array with one element for each character in the text. The character “R” goes into element 0, “u” into element 1, and so on, up to “r” in element 29.

The for loop in Lines 7–14 looks at each character in the mfl array. If the character is not a space, it is displayed. If it is a space, a ‘.’ character is displayed instead.

Multidimensional Arrays

The arrays thus far in the hour all have one dimension, so you can retrieve an element using a single number. Some types of information require more dimensions to store adequately as arrays, such as points in an (x,y) coordinate system. One dimension of the array could store the x coordinate, and the other dimension could store the y coordinate.

To create an array that has two dimensions, you must use an additional set of square brackets when creating and using the array, as in these statements:

boolean[][] selectedPoint = new boolean[50][50];
selectedPoint[4][13] = true;
selectedPoint[7][6] = true;
selectedPoint[11][22] = true;

This example creates an array of Boolean values called selectedPoint. The array has 50 elements in its first dimension and 50 elements in its second dimension, so there are 2,500 individual array elements (50 multiplied by 50). When the array is created, each element is given the default value of false. Three elements are given the value true: a point at the (x,y) position of 4,13, one at 7,6, and one at 11,22.

Arrays can have as many dimensions as you need, but keep in mind that they take up a lot of memory if they’re extremely large. Creating the 50 by 50 selectedPoint array was equivalent to creating 2,500 individual variables.

Sorting an Array

When you have grouped a bunch of similar items together into an array, one thing you can do is rearrange items. The following statements swap the values of two elements in an integer array called numbers:

int temporary = numbers[5];
numbers[5] = numbers[6];
numbers[6] = temporary;

These statements result in numbers[5] and numbers[6] trading values with each other. The integer variable called temporary is used as a temporary storage place for one of the values being swapped. Sorting is the process of arranging a list of related items into a set order, such as when a list of numbers is sorted from lowest to highest.

Santa Claus could use sorting to arrange the order of gift recipients by last name with Willie Aames and Hank Aaron raking in their Yuletide plunder much earlier than alphabetical unfortunates Dweezil Zappa and Jim Zorn.

Sorting an array is easy in Java because the Arrays class does all the work. Arrays, which is part of the java.util group of classes, can rearrange arrays of all variable types.

To use the Arrays class in a program, use the following steps:

1. Use the import java.util.* statement to make all the java.util classes available in the program.

2. Create the array.

3. Use the sort() method of the Arrays class to rearrange an array.

An array of variables that is sorted by the Arrays class is rearranged into ascending numerical order. Characters and strings are arranged in alphabetical order.

To see this in action, create a new Empty Java File named NameSorter and enter the text of Listing 9.2 in the source editor.

LISTING 9.2 The Full Source Code of NameSorter.java


1: package com.java24hours;
2:
3: import java.util.*;
4:
5: class NameSorter {
6: public static void main(String[] arguments) {
7: String names[] = { "Glimmer", "Marvel", "Rue", "Clove",
8: "Thresh", "Foxface", "Cato", "Peeta", "Katniss" };
9: System.out.println("The original order:");
10: for (int i = 0; i < names.length; i++) {
11: System.out.println(i + ": " + names[i]);
12: }
13: System.out.println();
14: Arrays.sort(names);
15: System.out.println("The new order:");
16: for (int i = 0; i < names.length; i++) {
17: System.out.println(i + ": " + names[i]);
18: }
19: System.out.println();
20: }
21: }


When you run this Java program, it displays a list of nine names in their original order, sorts the names, and then redisplays the list. Figure 9.2 shows the output.

Image

FIGURE 9.2 The output of the NameSorter program.

When you’re working with strings and the basic types of variables such as integers and floating-point numbers, you only can sort them by ascending order using the Arrays class. You can write code to do your own sorts by hand if you desire a different arrangement of elements during a sort or you want better efficiency than the Arrays class provides.

Counting Characters in Strings

The letters that appear most often in English are E, R, S, T, L, N, C, D, M, and O, in that order. This is a fact worth knowing if you ever find yourself on the syndicated game show Wheel of Fortune.


Note

If you’re unfamiliar with the show, Wheel of Fortune is a game in which three contestants guess the letters of a phrase, name, or quote. If they get a letter right and it’s a consonant, they win the amount of money spun on a big wheel. To re-create the experience, play hangman with your friends in front of a studio audience, hand out random amounts of money when someone guesses a letter correctly, and give the winner a new Amana stove.


Your next Java program counts letter frequency in as many different phrases and expressions as you care to type. An array is used to count the number of times that each letter appears. When you’re done, the program presents the number of times each letter appeared in the phrases.

Create a new Empty Java File in NetBeans called Wheel.java, fill it with the contents of Listing 9.3, and save the file when you’re finished. Feel free to add additional phrases between Lines 17 and 18, formatting them exactly like Line 17.

LISTING 9.3 The Full Source Code of Wheel.java


1: package com.java24hours;
2:
3: class Wheel {
4: public static void main(String[] arguments) {
5: String phrase[] = {
6: "A STITCH IN TIME SAVES NINE",
7: "DON'T EAT YELLOW SNOW",
8: "JUST DO IT",
9: "EVERY GOOD BOY DOES FINE",
10: "I WANT MY MTV",
11: "I LIKE IKE",
12: "PLAY IT AGAIN, SAM",
13: "FROSTY THE SNOWMAN",
14: "ONE MORE FOR THE ROAD",
15: "HOME FIELD ADVANTAGE",
16: "VALENTINE'S DAY MASSACRE",
17: "GROVER CLEVELAND OHIO",
18: "SPAGHETTI WESTERN",
19: "AQUA TEEN HUNGER FORCE",
20: "IT'S A WONDERFUL LIFE"
21: };
22: int[] letterCount = new int[26];
23: for (int count = 0; count < phrase.length; count++) {
24: String current = phrase[count];
25: char[] letters = current.toCharArray();
26: for (int count2 = 0; count2 < letters.length; count2++) {
27: char lett = letters[count2];
28: if ( (lett >= 'A') & (lett <= 'Z') ) {
29: letterCount[lett - 'A']++;
30: }
31: }
32: }
33: for (char count = 'A'; count <= 'Z'; count++) {
34: System.out.print(count + ": " +
35: letterCount[count - 'A'] +
36: " ");
37: if (count == 'M') {
38: System.out.println();
39: }
40: }
41: System.out.println();
42: }
43: }


If you run the program without adding your own phrases, the output should resemble Figure 9.3.

Image

FIGURE 9.3 The output of the Wheel program.

The following things are taking place in the Wheel program:

Image Lines 5–21—Phrases are stored in a string array called phrase.

Image Line 22—An integer array called letterCount is created with 26 elements. This array is used to store the number of times each letter appears. The order of the elements is from ‘A’ to ‘Z’. letterCount[0] stores the count for letter ‘A’, letterCount[1] stores the count for ‘B’, and so on, up to letterCount[25] for ‘Z’.

Image Line 23—A for loop cycles through the phrases stored in the phrase array. The phrase.length variable is used to end the loop after the last phrase is reached.

Image Line 24—A string variable named current is set with the value of the current element of the phrase array.

Image Line 25—A character array is created and stores all the characters in the current phrase.

Image Line 26—A for loop cycles through the letters of the current phrase. The letters.length variable is used to end the loop after the last letter is reached.

Image Line 27—A character variable called lett is created with the value of the current letter. In addition to their text value, characters have a numeric value. Because elements of an array are numbered, the numeric value of each character is used to determine its element number.

Image Lines 28–30—An if statement weeds out all characters that are not part of the alphabet, such as punctuation and spaces. An element of the letterCount array is increased by 1 depending on the numeric value of the current character, which is stored in lett. The numeric values of the alphabet range from 65 for ‘A’ to 90 for ‘Z’. Because the letterCount array begins at 0 and ends at 25, ‘A’ (65) is subtracted from lett to determine which array element to increase.

Image Line 33—A for loop cycles through the alphabet from ‘A’ to ‘Z’.

Image Lines 34–40—The current letter is displayed followed by a semicolon and the number of times the letter appeared in the phrases stored in the phrase array. When the current letter is ‘M’, a newline is displayed so the output is spread out over two lines.


Note

The numeric values associated with each of the characters from ‘A’ to ‘Z’ are those used by the ASCII character set. The ASCII character set is part of Unicode, the full character set supported by the Java language. Unicode includes support for more than 60,000 different characters used in the world’s written languages. ASCII is limited to just 256.


This project shows how two nested for loops can be used to cycle through a group of phrases one letter at a time. Java attaches a numeric value to each character; this value is easier to use than the character inside arrays.

Summary

Arrays make it possible to store complicated types of information in a program and manipulate that information. They’re ideal for anything that can be arranged in a list and can be accessed easily using the loop statements that you learned about during Hour 8, “Repeating an Action with Loops.”

To be honest, the information-processing needs of Santa Claus probably have outgrown arrays. More children are manufactured each year, and the gifts they want are constantly increasing in complexity and expense.

Your programs are likely to use arrays to store information that is unwieldy to work with using variables, even if you’re not making any lists or checking them twice.

Workshop

Q&A

Q. Is the numeric range of the alphabet, from 65 for ‘A’ to 90 for ‘Z’, part of the basic Java language? If so, what are 1 through 64 reserved for?

A. The numbers 1 through 64 include numerals, punctuation marks, and some unprintable characters, such as linefeed, newline, and backspace. A number is associated with each printable character that can be used in a Java program, as well as some unprintable ones. Java uses the Unicode numbering system. The first 127 characters are from the ASCII character set, which you might have used in another programming language.

Q. Why are errors called exceptions?

A. The significance of the term is that a program normally runs without any problems, and the exception signals an exceptional circumstance that must be dealt with. Exceptions are warning messages that are sent from within a Java program. In the Java language, the term error is sometimes confined to describe error conditions that take place within the interpreter running a program. You learn more about errors and exceptions during Hour 18.

Q. In a multidimensional array, is it possible to use the length variable to measure different dimensions other than the first?

A. You can test any dimension of the array. For the first dimension, use length with the name of the array, as in x.length. Subsequent dimensions can be measured by using length with the [0] element of that dimension. Consider an array called data that was created with the following statement:

int[][][] data = new int[12][13][14];

The dimensions of this array can be measured by using the data.length variable for the first dimension, data[0].length for the second, and data[0][0].length for the third.

Q. Why does New England Patriots head coach Bill Belichick always wear that ridiculous hoodie on the sidelines?

A. When you have the highest number of wins over a decade than any coach in NFL history—140 from 2003 to 2012—your boss lets you set your own dress code. Sportswriters believe that Belichick began wearing the cut-off hoodie in response to an NFL deal with Reebok that required all coaches to wear licensed team apparel.

“He decided that if they were going to make him wear team apparel then he’d sift through the options and put on the absolute ugliest thing he could find,” Dan Wetzel of Yahoo! Sports explained. “He chose a grey sweatshirt, often with a hood.”

Belichick’s passive-aggressive fashion statement has turned the hoodie into one of the team’s best-selling items.

Quiz

If your brain were an array, you could test its length by answering each of the following questions about arrays.

1. What types of information are arrays best suited for?

A. Lists

B. Pairs of related information

C. Trivia

2. What variable can you use to check the upper boundary of an array?

A. top

B. length

C. limit

3. How many reindeer does Santa have, including Rudolph?

A. 8

B. 9

C. 10

Answers

1. A. Lists that contain nothing but the same type of information—strings, numbers, and so on—are well-suited for storage in arrays.

2. B. The length variable contains a count of the number of elements in an array.

3. B. Santa had “eight tiny reindeer,” according to Clement Clarke Moore’s “A Visit from St. Nicholas,” so Rudolph makes nine.

Activities

To give yourself an array of experiences to draw from later, you can expand your knowledge of this hour’s topics with the following activities:

Image Create a program that uses a multidimensional array to store student grades. The first dimension should be a number for each student, and the second dimension should be for each student’s grades. Display the average of all the grades earned by each student and an overall average for every student.

Image Write a program that stores the first 400 numbers that are multiples of 13 in an array.

To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.