Download presentation
Presentation is loading. Please wait.
1
Arrays Mr. Smith AP Computer Science A
2
Java Concepts 7.1 (Arrays)
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)
3
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)
4
Java Concepts 7.1 (Arrays)
Conceptual Overview Each 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)
5
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)
6
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)
7
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 78 abc[1] = 66; //2nd element 66 abc[2] = (abc[0] + abc[1]) / 2; //3rd element average of first two abc[i] = 82; //4th element 82 because i is 3 abc[i + 1] = 94; //5th element 94 because i + 1 is 4 abc[499] = 76; //500th element 76 Java Concepts 7.1 (Arrays)
8
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)
9
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)
10
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)
11
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]; } If using an enhanced for loop (we will discuss this later): int sum = 0; for (int element : abc) // enhanced for loop { sum += element; } Java Concepts 7.1 (Arrays)
12
Java Concepts 7.4 (The Enhanced for Loop)
New to Java 5.0 Enhanced for loop a.k.a for each loop Java Concepts 7.4 (The Enhanced for Loop)
13
Java Concepts 7.4 (The 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)
14
Java Concepts 7.4 (The 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. 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 ) ; } Java Concepts 7.4 (The Enhanced for Loop)
15
Java Concepts 7.4 (The Enhanced for Loop)
An 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)
16
Java Concepts 7.4 (The Enhanced for Loop)
In 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)
17
Java Concepts 7.1 (Arrays)
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)
18
Java Concepts 7.4 (The 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)
19
TestScores Create 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.
20
TestScoresViewer The 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 }
21
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)
22
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 searchName int 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)
23
Java Concepts 7.1 (Arrays)
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 = new int[500]; // array of 500 integers int[] abc, xyz; abc = new int[500]; xyz = new int[10]; int[] abc = new int[500], xyz = new int[10]; Java Concepts 7.1 (Arrays)
24
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)
25
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 integers xyz = abc; //xyz and abc refer to the same array xyz[3] = 100; // Changing xyz changes abc as well. System.out.println (abc[3]); // 100 is displayed Java Concepts 7.1 (Arrays)
26
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 value int [] xyz = new int[10]; xyz[i] = abc[i]; Java Concepts 7.1 (Arrays)
27
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)
28
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. What would the following print to the console? int calcValue = abc[1]+abc[4]; System.out.println(calcValue); // prints 31 Java Concepts 7.1 (Arrays)
29
Java Concepts 7.1 (Arrays)
Declaring Arrays Here are arrays of doubles, booleans, Strings, and Students: 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." Java Concepts 7.1 (Arrays)
30
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)
31
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 , , , 20 }; Java Concepts 7.1 (Arrays)
32
Java Concepts 7.1 (Arrays)
Parallel Arrays Here is a visual way of looking at parallel arrays: names ages Bill 20 1 Sue 1 21 2 Shawn 2 19 3 Mary 3 24 4 Ann 4 20 Java Concepts 7.1 (Arrays)
33
Java Concepts 7.1 (Arrays)
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)
34
Java Concepts 7.1 (Arrays)
Parallel Arrays String[] name = {"Bill", "Sue", "Shawn", "Mary", "Ann"}; int[] age = {20 , 21 , , , 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)
35
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)
36
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 row column Java Concepts 7.6 (Two-Dimensional Arrays)
37
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)
38
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)
39
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 = 4 System.out.print(“Number of columns =“ + table[0].length); Number of columns = 5 Java Concepts 7.6 (Two-Dimensional Arrays)
40
Two-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: //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)
41
StudentTestScores class
Name Test Scores 1st 2nd rd 4th Gary 87 80 78 90 1 Susan 1 95 92 85 100 2 Bruce 2 62 75 70 81 3 Julie 3 105 75 80 92 4 Chuck 4 85 79 81 89 5 Luis 5 90 79 93 88 1 2 3 Note: You do not have to use these exact students or test scores
42
StudentTestScores Create 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.
43
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)
44
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 0 int[] abc = new int[50]; int size = 0; Java Concepts 7.1 (Arrays)
45
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)
46
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]; Show TestScores program at this point Java Concepts 7.1 (Arrays)
47
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)
48
Working with Arrays That Are Not Full
if (size < abc.length) { abc[size] = anInt; size++; } 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. Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)
49
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) remove Java Concepts 7.1 (Arrays), 7.7 (Copying Arrays)
50
Java Concepts Quality Tip 7.2 (pages 276-277)
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 )
51
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 it public void setName(String _name) { studentName = _name; } // Gets the name of student and passes it back to the calling program public String getName() return studentName; Java Concepts Quality Tip 7.2 (pages )
52
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 objects Student[] studentArray = new Student[10]; // Fill array with students studentArray[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 )
53
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 array System.out.println("The class average is " + sum / studentArray.length); ** Show Student and StudentTester classes Java Concepts Quality Tip 7.2 (pages )
54
Java Concepts 7.1 (Arrays)
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)
55
Java Concepts 7.1 (Arrays)
Arrays and Methods In the figure, the method changes the student's name to Bill, and after the method finishes executing, the name is still Bill. Actual Parameter …. Student student = new Student(“William”,90,91,83); doSomethingToStudent( student ); void doSomethingToStudent (Student studentParm) { studentParm.setName(“Bill”); } Student object Formal Parameter Java Concepts 7.1 (Arrays)
56
Java Concepts 7.1 (Arrays)
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)
57
Java Concepts 7.5 (Simple Array Algorithms)
Arrays and Methods Search 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)
58
Java Concepts 7.7 (Copying Arrays)
Arrays and Methods Copying an Array Write a method that will copy one array into another array. 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; Here is the call to the method: int[] orig = {1,2,3,4,5}; int[] cp = new int[5]; cp = copyArray(orig); Java Concepts 7.7 (Copying Arrays)
59
EmployeeNames Create 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.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.