59
Arrays Mr. Smith AP Computer Science A

Arrays Mr. Smith AP Computer Science A. Conceptual Overview An array consists of an ordered collection of similar items. An array has a single name, and

Embed Size (px)

Citation preview

Arrays

Mr. SmithAP Computer Science

A

Conceptual Overview

An array consists of an ordered collection of similar items.

An array has a single name, and the items in an array are referred to in terms of their position within the array.

An array makes it just as easy to manipulate a million test scores as it would to work with three test scores.

Java Concepts 7.1 (Arrays)

Conceptual Overview

The items in an array are called elements.

For any particular array, all the elements must be of the same type.

The type can be any primitive, String, or object data type.

For instance, we can have an array of test scores, an array of names, or even an array of Student objects.

Java Concepts 7.1 (Arrays)

Conceptual OverviewEach array below contains five elements (they each

have a length of 5). The first element in the array named test is referred to as test[0], the second as test[1], and so on.

An item's position within an array is called its index, subscript, or position (all these terms mean the same thing).

Java Concepts 7.1 (Arrays)

Simple Array Manipulations

First lets declare and instantiate an array of 500 integer values.

By default, all of the values are initialized to 0.

int[] abc = new int[500];

Java Concepts 7.1 (Arrays)

Simple Array Manipulations

The basic syntax for referring to an array element has the form:

Where <index> must be between 0 and (the array's length minus 1).

The subscript operator ([ ]) has the same precedence as the method selector (.).

<array name> [<index>] i.e. testScore[3]

Java Concepts 7.1 (Arrays)

Simple Array Manipulations

For example we assign values to the first five elements:

When assigning a value to the 500th element, we must remember that its index is 499, not 500:

int i = 3;abc[0] = 78; //1st element 78abc[1] = 66; //2nd element 66abc[2] = (abc[0] + abc[1]) / 2; //3rd element average of first twoabc[i] = 82; //4th element 82 because i is 3abc[i + 1] = 94; //5th element 94 because i + 1 is 4

abc[499] = 76; //500th element 76

Java Concepts 7.1 (Arrays)

Simple Array Manipulations

The JVM checks the values of subscripts before using them and throws an ArrayIndexOutOfBoundsException if they are out of bounds (less than 0 or greater than the array length - 1).

The detection of a range bound error is similar to the JVM's behavior when a program attempts to divide by 0.

Java Concepts 7.1 (Arrays)

Simple Array Manipulations

We frequently need to know an array's length.

The array itself makes this information available by means of a public instance variable called length:

System.out.println ("The size of abc is: " + abc.length);

Java Concepts 7.1 (Arrays)

Looping Through Arrays

Sum the Elements Team up with a partner if you’d like Write a loop that will sum all the elements

in array abc In 5 minutes we will discuss how to do this

Java Concepts 7.1 (Arrays)

Looping Through Arrays

Sum the Elements Each time through the loop adds a

different element to the sum. On the first iteration we add abc[0] and on the last abc[499].int sum = 0;

for (int i = 0; i < abc.length; i++){

sum += abc[i]; }

int sum = 0;for (int element : abc) // enhanced for loop{

sum += element; }

If using an enhanced for loop (we will discuss this later):

Java Concepts 7.1 (Arrays)

New to Java 5.0

Enhanced for loop a.k.a for each loop

Java Concepts 7.4 (The Enhanced for Loop)

Enhanced for Loop

This type of loop visits each element in an array from the first position to the last position.

On each pass through the loop, the element at the current position is automatically assigned to a temporary variable. No other loop control information is required.

Java Concepts 7.4 (The Enhanced for Loop)

Enhanced for Loop The syntax is much simpler than the standard for loop

for (<temp variable declaration> : <array object>) <statement>

The type of the temporary variable must be compatible with the element type of the array.

Java Concepts 7.4 (The Enhanced for Loop)

Printing all elements in an array using a Standard for loop:

for (int i = 0; i < abc.length; i++){ System.out.print( abc[i] ) ;}Printing all elements in an array using an Enhanced for loop:

for (int abcElement : abc ){ System.out.print( abcElement ) ;}

Enhanced for LoopAn enhanced for loop is clearly simpler to write than a standard for loop with an index. The enhanced for loop is also less error-prone because Java automates the setup and processing of the loop control information.

However, this type of loop cannot be used to: move through an array in reverse, from last

position to the first position add/change array elements track the index position of the current element

in an array access any element other than the current

element on each pass

Java Concepts 7.4 (The Enhanced for Loop)

Enhanced for LoopIn general, it’s also not a good idea to use an enhanced for loop on an array that’s not filled.So,

be sure the array is filled be sure that you’re going to visit each

element from the first to the last, Be sure that you don’t need to assign a

value to an element at a given position

Java Concepts 7.4 (The Enhanced for Loop)

Enhanced for Loop

To sum up all the elements in an array:

Using a Standard for loop:

int sum = 0;for (int i = 0; i < allScores.length; i++){

sum += allScores[i]; }

Using an Enhanced for loop:

int sum = 0;for (int score : allScores) // enhanced for loop{

sum += score; }

Java Concepts 7.1 (Arrays)

Enhanced for Loop

Beginning in 2007, students started seeing the “for each” loop in AP Exams.

There aren’t any “trick questions” – the for each loop will simply be used in situations in which students shouldn’t waste time with indexes or iterators.

Java Concepts 7.4 (The Enhanced for Loop)

TestScoresCreate a TestScores class and TestScoresViewer client class to do the following. The TestScores class should contain the following two methods:

Write a inputScores() method that continually prompts the user for test scores. No more than ten test scores should be entered. Test scores are integer values between 0 and 110 (we’ll assume that up to 10 points extra credit could be allowed on a test). Use an input dialog window (use the JOptionPane.showInputDialog method).

If the user enters “999” then that indicates they are finished entering values, and the program should exit out of the loop.

Convert each test score entered into an integer and store it into an array. Keep track of how many test scores are entered.

Write a processScores() method that loops through this test scores array as follows:

Read each value from the test scores array. Print each test score to the console on one line, separated by commas

(i.e. 100, 90, 85, 70). Print the lowest test score to the console. Print the highest test score to the console. Print the average test score to the console.

Note: When printing values to the console, be descriptive.

TestScoresViewerThe TestScoresViewer client class should look like the following:

public class TestScoresViewer {

public static void main(String[] args) {

TestScores scores = new TestScores();scores.inputScores(); //input all test scores

scores.processScores(); //print scores, min, max, and average

}}

Looping Through Arrays

Count the Occurrences Array studentNames is an array of String

values. Each element contains a first name of a student in the class. Assume that variable searchName is a String that contains the name you want to search for. Write an enhanced for loop that will count the number of times the value of variable searchName appears in the array studentName.

Java Concepts 7.4 (The Enhanced for Loop)

Looping Through Arrays

Count the Occurrences We can determine how many times String

searchName occurs in the array by comparing searchName to each element and incrementing count every time there is a match:

String searchName = “Tom”; //Assign some value to searchNameint count = 0;

for (String name : studentNames ){ if (name.equals(searchName)) count++; //Found another element equal to

//searchName}

Java Concepts 7.4 (The Enhanced for Loop)

Declaring Arrays

Arrays are objects and must be instantiated before being used.

Several array variables can be declared in a single statement like this:

Or like this:

int[] abc, xyz;abc = new int[500];xyz = new int[10];

int[] abc = new int[500], xyz = new int[10];

int[] abc = new int[500]; // array of 500 integers

Java Concepts 7.1 (Arrays)

Declaring Arrays

Array variables are null before they are instantiated and assigned array objects.

Failure to assign an array object can result in a null pointer exception.

int[] abc;abc[1] = 10; // runtime error: null pointer exception

Java Concepts 7.1 (Arrays)

Declaring Arrays

Because arrays are objects, two variables can refer to the same array

int[] abc, xyz;abc = new int[5]; //Instantiate an array of 5 integersxyz = abc; //xyz and abc refer to the same arrayxyz[3] = 100; // Changing xyz changes abc as well.System.out.println (abc[3]); // 100 is displayed

Java Concepts 7.1 (Arrays)

Declaring Arrays

If we want abc and xyz to refer to two separate arrays that happen to contain the same values, we would copy all of the elements from one array to the other as follows.

int[] abc = new int[10];for (int i = 0; i < 10; i++) abc[i] = i; // or any valueint [] xyz = new int[10];for (int i = 0; i < 10; i++) xyz[i] = abc[i];

Java Concepts 7.1 (Arrays)

Declaring Arrays

Because arrays are objects, Java’s garbage collector sweeps them away when they are no longer referenced.

int [] abc = new int[10]; int [] xyz = new int[5];xyz = null; // the array is no longer referenced so // the garbage collector will sweep it away.

Java Concepts 7.1 (Arrays)

Declaring Arrays

Arrays can be declared, instantiated, and initialized in one step.

The list of numbers between the braces is called an initializer list.

int[] abc = {10,20,25,9,11}; // abc now references an array of five integers.

Java Concepts 7.1 (Arrays)

What would the following print to the console?int calcValue = abc[1]+abc[4];System.out.println(calcValue); // prints 31

Declaring Arrays

double[] ddd = new double[10];boolean[] bbb = new boolean[10];String[] ggg = new String[10];Student[] sss = new Student[10];String str; ddd[5] = 3.14;bbb[5] = true;ggg[5] = "The cat sat on the mat.";sss[5] = new Student();sss[5].setName ("Bill");str = sss[5].getName() + ggg[5].substring(7); // str now equals "Bill sat on the mat."

Here are arrays of doubles, booleans, Strings, and Students:

Java Concepts 7.1 (Arrays)

Declaring Arrays

There is another way to declare array variables.

int aaa[]; // aaa is an array variable

int bbb[], ccc, ddd[]; // bbb and ddd are arrays, // but ccc is an integer

Java Concepts 7.1 (Arrays)

Parallel Arrays

Parallel Arrays – Separate arrays of the same length that correspond to one another. They could have different component data types.

Suppose we want to keep a list of people's names (Strings) and ages (integers).

This can be achieved by using two parallel arrays in which corresponding elements are related.

Thus, Bill's age is 20 and Mary's age is 24.

String[] name = {"Bill", "Sue", "Shawn", "Mary", "Ann"};int[] age = {20 , 21 , 19 , 24 , 20 };

Java Concepts 7.1 (Arrays)

Parallel Arrays

Here is a visual way of looking at parallel arrays:

Java Concepts 7.1 (Arrays)

names

Bill

Sue

Shawn

Mary

Ann

0

1

2

3

4

0

1

2

3

4

ages

20

21

19

24

20

Parallel Arrays

The next slide shows a segment of code that finds the age of a particular person.

In this example, the parallel arrays are both full and the loops use the instance variable length.

When the arrays are not full, the code will need an extra variable to track their logical sizes.

Java Concepts 7.1 (Arrays)

Parallel ArraysString[] name = {"Bill", "Sue", "Shawn", "Mary", "Ann"};int[] age = {20 , 21 , 19 , 24 , 20 }; int correspondingAge = -1;int i; String searchName = JOptionPane.showInputDialog("What name do you want to search for?");for (i = 0; i < name.length; i++){ if (searchName.equals(name[i])) { correspondingAge = age[i]; break; }}if (correspondingAge == -1) System.out.println(searchName + " was not found.");else System.out.println(searchName + " is " + correspondingAge + " years old.");

Java Concepts 7.1 (Arrays)

Two-Dimensional Arrays

Starting in May 2010, Two-Dimensional Arrays will be included on the AP Exam.Prior to 2010, two-dimensional arrays were not included on the AP Exam except in the case study

Java Concepts 7.6 (Two-Dimensional Arrays)

Two-Dimensional Arrays A table of numbers, for instance, can be

implemented as a two-dimensional array. The figure shows a two-dimensional array with four rows and five columns.

Suppose we name this array table; then to indicate an element in table, we specify its row and column position, remembering that indexes start at 0:int x = table[2][3]; // Sets x to 11, the value

// in row 2, column 3

Java Concepts 7.6 (Two-Dimensional Arrays)row column

col 0 col 1 col 2 col 3 col 4

row 0 20 10 45 72 90

row 1 30 25 60 32 45

row 2 10 12 71 11 62

row 3 15 8 53 84 14

Two-Dimensional Arrays

Declare and Instantiate Declaring and instantiating two-

dimensional arrays is accomplished by extending the processes used for one-dimensional arrays:

int[][] table = new int [4][5]; // The variable named table can reference a // two-dimensional array of integers. // Instantiate table as an array of size 4, // each of whose elements will reference an // array of 5 integers.

Java Concepts 7.6 (Two-Dimensional Arrays)

Two-Dimensional Arrays

Initializer lists can be used with two-dimensional arrays. This requires an array of arrays.

The number of inner lists determines the number of rows, and the size of each inner list determines the size of the corresponding row.

The rows do not have to be the same size, but they are in this example: int[][] table = {{ 0, 1, 2, 3, 4}, // row 0

{10,11,12,13,14}, // row 1 {20,21,22,23,24}, // row 2 {30,31,32,33,34}}; // row 3

Java Concepts 7.6 (Two-Dimensional Arrays)

Two-Dimensional Arrays

Remember, all the elements of a two-dimensional array must be of the same type, whether they are integers, doubles, Strings, or whatever.

To determine the number of rows in the 2-dimensional array, you can use the length variable (just like a 1-dimensional array).

To determine the number of columns in the 2-dimensional array, you can use the length variable for an array element.

If we refer to the table 2-dim array from the previous slide, what would the following print to the console?

System.out.print(“Number of rows =“ + table.length); Number of rows = 4System.out.print(“Number of columns =“ + table[0].length); Number of columns = 5

Java Concepts 7.6 (Two-Dimensional Arrays)

Two-Dimensional Arrays

//The following code will print every student in each class

String[][] students = {{"Bill", "Brenda", "Bob", "Bonnie"}, {"Sally", "Sam", "Sandra", "Steve"}}; for (int row = 0; row < students.length; row++) //loops thru rows{ System.out.println(""); System.out.print("These students are in period " + (row+1) + ": " );

for (int col = 0; col < students[0].length; col++) //loops thru columns { System.out.print( students[row][col] + ", " ); }}

Java Concepts 7.6 (2-Dimensional Arrays)

The following code uses a two-dimensional array. Each row represents a class period and each column represents the students in that class:

StudentTestScores class

StudentName

87Gary 80 78 90

Susan

Bruce

Julie

Chuck

95 92 85 100

62 75 70 81

105 75 80 92

85 79 81 89

Test Scores

1st 2nd 3rd 4th 0

1

2

3

4

0 1 2 3

0

1

2

3

4

Luis 90 79 93 885 5

Note: You do not have to use these exact students or test scores

StudentTestScoresCreate a StudentTestScores class and StudentTestScoresViewer client class:In the StudentTestScores class, create a method named printTestScores():

This class should keep track of test scores for multiple students. Test scores are integer values between 0 and 110 (we’ll assume that up to 10 points extra credit could be allowed on a test).

Create a normal one-dimensional array to keep track of student names. Use an initializer list to populate this array with 6 student names (6 elements).

Create a two-dimensional array to keep track of multiple test scores per student. 4 tests have been taken by each student. Each row number of this array will correspond to the index of the student from the

“student names” array you just created. Each column represents one of the four test scores for the student. Use an initializer list to populate the test scores for each student.

Write a loop to process the two arrays as follows: Loop through each student in the student array For each student, loop through the corresponding test scores for that student Output the student name and a list of his/her test scores to the console similar to the

following. Also, calculate the average test score for the student:Bill had test scores of 75, 80, 80, 85. Test average is 80.0

Test with a couple scenarios EXTRA CREDIT (5 points):

Print the lowest test score (and the name of the person that had it) to the console. Print the highest test score (and the name of the person that had it) to the console. Print the class average test score (for all students in the class) to the console.

Working with Arrays That Are Not Full

One might create an array of 20 ints but receive only 5 ints from interactive input (remember the TestScores program).

This array has a physical size of 20 cells but a logical size of 5 cells currently used by the application.

From the application's perspective, the remaining 15 cells contain garbage.

Java Concepts 7.1 (Arrays)

Working with Arrays That Are Not Full

It is possible to track the array's logical size with a separate integer variable.

The following code segment shows the initial state of an array and its logical size: Note that abc.length (the physical size)

is 50, whereas size (the logical size) is 0int[] abc = new int[50];int size = 0;

Java Concepts 7.1 (Arrays)

Working with Arrays That Are Not Full

Processing Elements in an Array That Is Not Full

When the array is not full, one must replace the array's length with its logical size in the loop.

Here is the code for computing the sum of the integers currently available in the array abc:

Java Concepts 7.1 (Arrays)

Working with Arrays That Are Not Full

int[] abc = new int[50];int size = 0; ... code that puts values into some initial portion of the array and sets the value of size (i.e. like capturing scores in TestScores program)

Then you can use the size in the remaining code in the program: int sum = 0;for (int i = 0; i < size; i++) // size contains

//the number of items in the array sum += abc[i];

Java Concepts 7.1 (Arrays)Show TestScores program at this point

Working with Arrays That Are Not Full

Inserting Elements into an Array The simplest way to insert a data

element into an array is to place it after the last populated item in the array.

One must first check to see if there is an element available (make sure you are not going over the array’s length) and then remember to increment the array's logical size.

The following code shows how to insert an integer at the end of array abc:

Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)

Working with Arrays That Are Not Full

When size equals abc.length, the array is full. The if statement prevents a range error

(ArrayIndexOutOfBoundsException) from occurring.

Remember that Java arrays are of fixed size when they are instantiated, so eventually they could become full.

if (size < abc.length){ abc[size] = anInt; size++;}

Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)

Working with Arrays That Are Not Full

Removing Elements from an Array Removing a data element from the end of

an array requires no change to the array itself.

Simply decrement the logical size variable, thus preventing the application from accessing the garbage elements beyond that point (since your program would always be checking the size variable when processing the array).

Note: It is not necessary, but depending on the situation you may want to set the element’s value to the value assigned at its initial state (i.e. 0 if it is an int array, or null if it is a String array)

Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)

remove

Arrays of Objects Here is the Student class that we are

referring to in the following slides: public class Student { String studentName; int[] scores = new int[3];

//Constructor method for Student object public Student (String _studentName, int _score1, int _score2, int _score3) { studentName = _studentName; scores[0] = _score1; scores[1] = _score2; scores[2] = _score3; }

public double getAverage() //Returns the average for the student { double sum = 0; for (int i=0; i<scores.length; i++) { sum += scores[i]; } if (scores.length > 0) return sum / scores.length; else return -1; }}

Java Concepts Quality Tip 7.2 (pages 276-277)

Arrays of Objects Here are other useful methods in the

Student class:

// Sets the name of the student to the name passed to itpublic void setName(String _name){ studentName = _name;}

// Gets the name of student and passes it back to the calling programpublic String getName(){ return studentName;}

Java Concepts Quality Tip 7.2 (pages 276-277)

Arrays of Objects Arrays can hold objects of any type, or more

accurately, references to objects. For example, if we created a Student class

object, we could declare, instantiate and fill an array of students as follows:

When an array of objects is instantiated, each cell is null by default until assigned a new object.

// Declare and reserve 10 cells for student objectsStudent[] studentArray = new Student[10]; // Fill array with studentsstudentArray[0] = new Student("Tom", 100, 85, 90);studentArray[1] = new Student("Sally", 80, 72, 70);studentArray[2] = new Student("Jerry", 91, 88, 85);studentArray[3] = new Student("Marsha", 99, 81, 85);studentArray[4] = new Student("Phil", 93, 85, 72);studentArray[5] = new Student("Evan", 77, 88, 99);studentArray[6] = new Student("Paula", 86, 65, 80);studentArray[7] = new Student("Courtney", 71, 75, 62);studentArray[8] = new Student("Johnny", 60, 65, 56);studentArray[9] = new Student("Cheryl", 104, 99, 90);

Java Concepts Quality Tip 7.2 (pages 276-277)

Arrays of Objects

The following code segment prints the average of all students in the studentArray. Pay special attention to the technique used to send a message to objects in an array:

// Print the average of all students in the array. double sum = 0;for (int i = 0; i < studentArray.length; i++){ sum += studentArray[i].getAverage(); //Send message to object } //in arraySystem.out.println("The class average is " + sum / studentArray.length);

Java Concepts Quality Tip 7.2 (pages 276-277)

** Show Student and StudentTester classes

Arrays and Methods

When any object is used as a parameter to a method, what actually gets passed is a reference to the object and not the object itself.

The actual and formal parameters refer to the same object, and changes the method makes to the object's state are still in effect after the method terminates.

Java Concepts 7.1 (Arrays)

Arrays and MethodsIn the figure, the method changes the student's name to Bill, and after the method finishes executing, the name is still Bill.

Java Concepts 7.1 (Arrays)

….Student student = new Student(“William”,90,91,83);doSomethingToStudent( student );….void doSomethingToStudent (Student studentParm){

….studentParm.setName(“Bill”);….

}

Studentobject

Actual Parameter

Formal Parameter

Arrays and Methods

Arrays are objects, so the same rules apply. When an array is passed as a parameter to a

method, the method manipulates the array itself and not a copy of the array.

Changes made to the array in the method are still in effect after the method has completed its execution.

Passing an array to a method leads to trouble if the method accidentally mishandles the array.

A method can also instantiate a new object or a new array and return it using the return statement.

Java Concepts 7.1 (Arrays)

Arrays and MethodsSearch for a Value

The code to search an array for a value is used so frequently in programs that it is worth placing in a method.

Here is a method to search an array of integers. The method returns the location of the first array element

equal to the search value or -1 if the value is not there:

static int search (int[] a, int searchValue){ int location, i; location = -1; for (i = 0; i < a.length; i++) { if (a[i] == searchValue) { location = i; break; } } return location;}

Java Concepts 7.5 (Simple Array Algorithms)

Arrays and Methods

Here is the call to the method:

static int[] copyArray(int[] original){ int[] copy = new int[original.length]; for (int i = 0; i < original.length; i++) { copy[i] = original[i]; } return copy;}

int[] orig = {1,2,3,4,5};int[] cp = new int[5];

cp = copyArray(orig); Java Concepts 7.7 (Copying Arrays)

Copying an Array Write a method that will copy one array into another array.

EmployeeNamesCreate an EmployeeNames class and EmployeeNamesTester client class to do the following:

You are a programmer for a company of 10 employees. The owner of the company only hires people whose first name begins with the last character of their last name and their middle name begins with the next-to-last character in their last name (i.e. H. T. Smith or Z. E. Lopez). You have been given only the last names of each employee and have been asked to generate a list of employee names using the first and middle initials (i.e. you were given Jones, you need to print S. E. Jones). Since your boss is very controlling and wants to make sure that you know how to pass arrays to methods, he has given you the following strict instructions on how to create the program:

Your EmployeeNames class needs to have a static method named convertName(). This method will be the only method in this class and should do the following:

The method should accept an array of last names as the input parameter. The method should return an array of formatted names (first and middle initials and last name) Loop through the array of last names that is sent to the method. For each element, it should determine the first initial and middle initial of the name and format it correctly (H. T.

Smith) It should store each of these formatted names as elements in a formatted names array. After processing all the names, the method should return the formatted names array back to the calling program.

Create a driver program named EmployeeNamesTester. Create a main() method in this class and do the following in the main() method:

Create an array of employee last names (there are up to 10 employees). You need to populate this array with last names by either using an initializer list or prompting the user (see extra credit).

Declare and instantiate an array of formatted names that will be used to store the name with first and middle initials.

Call the EmployeeNames.convertName method and pass it the array of last names. Assign the returned array to the formatted names array you created in the main method. Loop through the formatted names and print them to the console on separate lines.

EXTRA CREDIT (5 points): Input the last names instead of using an initializer list and handle the situation where the last names array is not

full.