1 / 59

Arrays

Learn about arrays in Java, including their structure, element types, indexing, manipulation, and looping techniques. Understand the enhanced for loop and its limitations.

allegra
Download Presentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays Mr. Smith AP Computer Science A

  2. 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. 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. 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. New to Java 5.0 • Enhanced for loop • a.k.a for each loop Java Concepts 7.4 (The Enhanced for Loop)

  13. 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. 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. 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. 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. 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. 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: publicclass TestScoresViewer { publicstaticvoid 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. 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. 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. 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. 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]; for (int i = 0; i < 10; i++) xyz[i] = abc[i]; Java Concepts 7.1 (Arrays)

  27. 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. 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. 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. 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. 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)

  32. Parallel Arrays • Here is a visual way of looking at parallel arrays: names ages 0 Bill 0 20 1 Sue 1 21 2 Shawn 2 19 3 Mary 3 24 4 Ann 4 20 Java Concepts 7.1 (Arrays)

  33. 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. Parallel Arrays String[] 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)

  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 column row 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 Test Scores Student Name 1st 2nd 3rd 4th 0 Gary 0 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 0 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 remove 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)

  50. Arrays of Objects • Here is the Student class that we are referring to in the following slides: publicclass Student { String studentName; int[] scores = newint[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; } publicdouble 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)

More Related