29
© 2012 Pearson Education, Inc. All rights reserved. Chapter 8: Arrays Starting Out with Java: From Control Structures through Data Structures Second Edition by Tony Gaddis and Godfrey Muganda

Final Gaddis Ch8 Arrays

  • Upload
    anika

  • View
    244

  • Download
    1

Embed Size (px)

DESCRIPTION

Java Programming: Gaddis textbook chapter 8, Array and Array lists powerpoint

Citation preview

Page 1: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Chapter 8:Arrays

Starting Out with Java: From Control Structures through Data Structures

Second Edition

by Tony Gaddis and Godfrey Muganda

Page 2: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Activity - Rules of the “Vocabulary Game”

1.) The Team that has the greatest participation will win 10 points extra credit for each team member.

2.) Each person in table must write a definition or example of a concept.

3.) Main* topics to take notes about or provide an example:a.) How to define an arrayb.) Two ways to initialize an array c.) How to access any element in an arrayd.) A loop used to traverse an arraye.) What is a parallel array?f.) How to check the bounds of an array, prevent off-by-one errors?*Feel free to take notes/give examples about any other topics related to arrays.

Page 3: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-3

Introduction to Arrays

• Primitive variables are designed to hold only one value at a time.

• Arrays allow us to create a collection of like values that are indexed.

• An array can store any type of data but only one type of data at a time.

• An array is a list of data elements.

Page 4: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-4

Creating Arrays• An array is an object so it needs an object reference.

// Step 1: Declare a reference to an array that will hold integers.

int[] numbers;

// Step 2: Create a new array that will hold 6 integers.

numbers = new int[6];

Array element values are initialized to 0.Array indexes always start at 0.

0index 0

0index 1

0index 2

0index 3

0index 4

0index 5

Page 5: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-5

Creating Arrays~ continued

• It is possible to declare an array reference and create it in the same statement.

// Declare and instantiate in 1 Step:

int[] numbers = new int[6];Note: Once created, an array size is fixed and cannot be changed.

Arrays may be of any type.

float[] temperatures = new float[100];char[] letters = new char[41];long[] units = new long[50];double[] sizes = new double[1200];String [] names = new String[10];

Page 6: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-6

Accessing the Elements of an Array

• An array is accessed by:– the reference name– An index that identifies which element in the array to access.

numbers[0] = 20; //pronounced "numbers at index zero"

numbers[0]

0numbers[1]

0numbers[2]

0numbers[3]

0numbers[4]

0numbers[5]

20

Page 7: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Traversing an Array – to populate it

Scanner keyboard = new Scanner(System.in);int[] numbers = new int[10];

forfor (int i = 0; i < 10; i++){

System.out.println(“Enter a number”); numbers[i] = keyboard.nextInt();

}

Page 8: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Traversing an Array – to access it

forfor (int i = 0; i < 10; i++){

System.out.println(“Number: ” + numbers[i]);

}

The Enhanced for Loop – an alternative to accessing the array

for(int val : numbers){

System.out.println(“Number: " + val);}

Enhanced for-Loops = simplified array processing (read only)Always goes through all elements

for(datatype elementVariable : array) { statement;}

Page 9: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-9

Array Initialization – an alternative

• When relatively few items need to be initialized, an initialization list can be used to initialize the array.

int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

• The numbers in the list are stored in the array in order:– days[0] is assigned 31,– days[1] is assigned 28,– days[2] is assigned 31,– days[3] is assigned 30,– etc.

Page 10: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-10

Bounds Checking

• Array indexes always start at zero and continue to (array length - 1).

int[] values = new int[10];

• This array would have indexes 0 through 9.

• In for loops, it is typical to use i, j, and k as counting variables.– It might help to think of i as representing the word index.

Page 11: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-11

Off-by-One Errors

• It is very easy to be off-by-one when accessing arrays.

// This code has an off-by-one error.

int[] numbers = new int[10];forfor (int i = 11; i <= 1010; i++){numbers[i] = 0;}

• Here, the equal sign allows the loop to continue on to index 10, where 9 is the last index in the array.

• This code would throw an ArrayIndexOutOfBoundsException.

Index out of bounds

Page 12: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

The length field & the length method

Arrays have a final field named length.

Use the .length field to check for boundaries of a table

forfor (int i = 11; i < numbers.length; i++){numbers[i] = 0;}

for (int i = 0; i < names.length; i++) System.out.println(names[i].length());

String objects have a method named length().

Page 13: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Activity

1.) Let’s define an array of your top 10 favorite music artists.

2.) Create a for-loop to ask the user for each name of their fav artist.

a.) Use the for-loop index as the index of the array.

3.) Create a separate (parallel) array of your favorite song for each artist, in exactly the same order as the artist array.

a.) Use the for-loop again to initialize it.

4.) Print the 2 parallel arrays, formatting the output so that the artist name is printed first, and beside it favorite song for that artist.

Page 14: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Activity – Another Round of the “Vocabulary Game”

1.) The Team that has the greatest participation will win 10 points extra credit for each team member. Each person in table must write a definition or example of a concept.

2.) Main* topics to take notes about & provide an example:

a.) How to copy an array

b.) How to receive an array as a parameter, & return an array from a method.

c.) How to compare elements in 2 arrays

d.) How to find:1.) highest & lowest element in an array

2.) sum & average of all elements in an array

Page 15: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-15

Copying Arrays• This is not the way to copy an array.

int[] array1 = { 2, 4, 6, 8, 10 };int[] array2 = array1; //This does not copy arrays.

2

Addressarray1 holds anaddress to the array

Addressarray2 holds anaddress to the array

4 6 8 10

2 reference variables, are pointing to one array in memory.

InsteadInstead, you need to copy each element of one array to another:

int[] firstArray = {5, 10, 15, 20, 25 };int[] secondArray = new int[5];

for (int i = 0; i < firstArray.length; i++)for (int i = 0; i < firstArray.length; i++){ secondArray[i] = firstArray[i]; }{ secondArray[i] = firstArray[i]; }

Right Way

!!!

Page 16: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-16

Passing Arrays as Arguments

• Arrays are objectsobjects.• Their references can be passed to methods like any

other object reference variable.

5 10 15 20 25

Address

showArray(numbersnumbers); 30 35 40

public static void showArray((int[] arrayarray)){ for (int i = 0; i < array.length; i++) System.out.print(array[i] + " ");}

Page 17: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-17

Returning an Array Reference• A method can return a reference to an array.• The return type of the method must be declared as an array of

the right type.

public static double[] double[] getArray(){ double[] array = { 1.2, 2.3, 4.5, 6.7, 8.9 }; return array;}

• The getArraygetArray method is a public static method that returns an array of doubles.

• Note: If you are receiving an array as a parameter, you do not have to explicitly return it as a return type, since any changes done to the array in the method will be permanent, even outside the method.

Page 18: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-18

Comparing Arrays: An Exampleint[] firstArray = { 2, 4, 6, 8, 10 };int[] secondArray = { 2, 4, 6, 8, 10 };boolean arraysEqual = true;int i = 0;

// First determine whether the arrays are the same size.if (firstArray.length != secondArray.length) arraysEqual = false;

// Next determine whether the elements contain the same data.while (arraysEqual && i < firstArray.length){ if (firstArray[i] != secondArray[i]) arraysEqual = false; i++;}

if (arraysEqual) System.out.println("The arrays are equal.");else System.out.println("The arrays are not equal.");

Why is it better to use a while

loop here?

Page 19: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-19

Useful Array Operations

• Finding the Highest Valueint [] numbers = {7, 3, 1, 9, 5};int highest = numbers[0];for (int i = 1; i < numbers.length; i++){if (numbers[i] > highest)highest = numbers[i];}

• Finding the Lowest Valueint lowest = numbers[0];for (int i = 1; i < numbers.length; i++){if (numbers[i] < lowest)lowest = numbers[i];}

Page 20: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-20

More Useful Array Operations• Summing Array Elements:

int total = 0; // Initialize accumulatorfor (int i = 0; i < units.length; i++) { total += units[i]; }

• Averaging Array Elements:double total = 0; // Initialize accumulatordouble average; // Will hold the averagefor (int i = 0; i < scores.length; i++){ total += scores[i]; }

average = total / scores.length;

Page 21: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Activity

1.) In main, define an array of your own grades, where each element of the array is the score you received on each of your labs and homework assignments (define & initialize in 1 step).

2.) In the same driver class, create a static method called calculateGradesStatistics(double[] myArray). This method will receive your array of grades as an input parameter.

3.) In the method, use a for-loop that will determine:a.) The highest scoreb.) The lowest scorec.) The sum of all the scoresd.) The average of all the scorese.) Print each of the above statistics after the for-loop is over.

Page 22: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Activity – Final Round of the “Vocabulary Game”

1.) The Team that has the greatest participation will win 10 points extra credit for each team member. Each person in table must write a definition or example of a concept.

2.) Main* topics to take notes about or provide an example:

a.) How to save an array to a file, & load an array from a file

b.) How to create & use an array of String objects

c.) How to create an array of any object

Page 23: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-23

Arrays and Files ~ Saving an array to a file

• Saving the contents of an array to a file:

int[] numbers = {10, 20, 30, 40, 50};

PrintWriter outputFile = new PrintWriter ("Values.txt");

for (int i = 0; i < numbers.length; i++) outputFile.println(numbers[i]);

outputFile.close();

Page 24: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-24

Arrays & Files ~ Loading an array from a file

• Reading the contents of a file into an array:

final int SIZE = 5; // Assuming we know the size.int[] numbers = new int[SIZE]; int i = 0;File file = new File ("Values.txt");Scanner inputFile = new Scanner(file);while (inputFile.hasNext() && i < numbers.length){ numbers[i] = inputFile.nextInt();inputFile.nextInt(); i++;}inputFile.close();

Page 25: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-25

String Arrays ~ Define & Initialize in 1 Step:

• An array of String objects can be created:

String[] names = { "Bill", "Susan", "Steven", "Jean" };

The names variable holdsthe address to the array.

A String array is an arrayof references to String objects.

Address

“Bill”

“Susan”

“Steven”

“Jean”

address

address

address

address

names[1]

names[0]

names[3]

names[2]

Page 26: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

String Arrays ~ Using 2 Steps:

• If an initialization list is not provided, the new keyword must be used to create the array:

String[] names = newnew String[4];

The names variable holdsthe address to the array.

Address

null

null

null

null

names[1]

names[0]

names[3]

names[2]

When an array is created in this manner, each element of the array must be initialized.

names[0] = "Bill";names[1] = "Susan";names[2] = "Steven";names[3] = "Jean";

Page 27: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-27

Using String Methods On each element of a String Array

• String objects have several methods, including:– toUpperCase– compareTo– equals– charAt

• Each element of a String array is a StringString object object.

• String Methods can be used by referencing the array name and index:

System.out.println(names[0].toUpperCase());names[0].toUpperCase());char letter = names[3].charAt(0);names[3].charAt(0);

Page 28: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved. 8-28

Arrays of Objects – An Alternative to Parallel Arrays

• This is an array of references to BankAccount objects:

BankAccount[] accounts = new BankAccount[5];The accounts variable holds the addresof an BankAccount array.

Address

null

null

null

null

accounts[1]accounts[0]

accounts[3]accounts[2]

nullaccounts[4]

Each element needs to be initialized.for (int i = 0; i < accounts.length; i++)for (int i = 0; i < accounts.length; i++)

{ accounts[i] = new BankAccount();}{ accounts[i] = new BankAccount();}

balance: 0.0

balance:

balance:

balance:

balance:

0.0

0.0

0.0

0.0

Page 29: Final Gaddis Ch8 Arrays

© 2012 Pearson Education, Inc. All rights reserved.

Final Array Activity – In 2 GroupsGroup 1 in Table:1.) Let’s create a text file, students.txt, that will contain the following fields, separated by a space: a.) Last Name b.) First Name c.) Student ID d.) GPACreate a new Netbeans Project, and copy the students.txt file in the same directory as the project.

2.) Define a Student class, with the 4 attributes defined above. Create a .toString() method in the Student class, that will return the first name + last name + student id + GPA.

Group 2 in Table:3.) Define a Driver class. In the main method, read each record from students.txt, and create a Student object from each record. Call a static method that will receive the name of the students.txt file, and will create and return an array of Student objects.

4.) Print the array of Student objects.

5.) Copy the selectionSort() method from Lab #7 to the bottom of the Driver class. Adjust the logic to sort by GPA.

6.) Invoke the selection sort method, passing it the array of Student objects. Print the array of Student objects again (should be sorted).