21
Two Dimensional Arrays Two Dimensional Arrays Found in chapter 8, Found in chapter 8, Section 8.9 Section 8.9

Two Dimensional Arrays Found in chapter 8, Section 8.9

Embed Size (px)

DESCRIPTION

Review  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.

Citation preview

Page 1: Two Dimensional Arrays Found in chapter 8, Section 8.9

Two Dimensional ArraysTwo Dimensional Arrays

Found in chapter 8, Section 8.9Found in chapter 8, Section 8.9

Page 2: Two Dimensional Arrays Found in chapter 8, Section 8.9

IntroductionIntroduction

Where have you seen them?Where have you seen them? When do we need them?When do we need them? Why are they useful?Why are they useful? How do we declare them?How do we declare them? How do we access them?How do we access them?

Page 3: Two Dimensional Arrays Found in chapter 8, Section 8.9

ReviewReview

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

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

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

An array is a list of data elements.An array is a list of data elements.

Page 4: Two Dimensional Arrays Found in chapter 8, Section 8.9

More ReviewMore Review

An array is an object so it needs an object An array is an object so it needs an object reference.reference.int[] numbers; int[] numbers; OR int number [];OR int number [];

//declares a reference to an array that will hold //declares a reference to an array that will hold integers.integers.

The next step creates the array and assigns The next step creates the array and assigns its address to the its address to the numbersnumbers variable variablenumbers = new int[6];numbers = new int[6];

//creates a new array that will hold 6 integers.//creates a new array that will hold 6 integers.

Page 5: Two Dimensional Arrays Found in chapter 8, Section 8.9

Accessing Array ElementsAccessing Array Elements An array is accessed by:An array is accessed by:

– the reference namethe reference name– a subscript that identifies which element in the array to a subscript that identifies which element in the array to

access.access.– ExamplesExamples

ArrayDemo1.javaArrayDemo1.java ArrayDemo2.javaArrayDemo2.java

Array Bounds CheckingArray Bounds Checking– ExamplesExamples

InvalidSubscript.javaInvalidSubscript.java ArrayIndexOutOfBoundsException.ArrayIndexOutOfBoundsException.

Page 6: Two Dimensional Arrays Found in chapter 8, Section 8.9

Initializing ArraysInitializing Arrays

When relatively few items need to be When relatively few items need to be initialized, an initialization list can be initialized, an initialization list can be used to initialize the array.used to initialize the array.int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,

31};31};

The numbers in the list are stored in The numbers in the list are stored in the array in order:the array in order:

ExampleExample ArrayInitialization.javaArrayInitialization.java

Page 7: Two Dimensional Arrays Found in chapter 8, Section 8.9

Processing Array ContentsProcessing Array Contents Processing data in an array is the same as any other Processing data in an array is the same as any other

variable.variable.grossPay = hours[3] * payRate;grossPay = hours[3] * payRate;

Pre and post increment works the same:Pre and post increment works the same:int[] score = {7, 8, 9, 10, 11};int[] score = {7, 8, 9, 10, 11};++score[2]; // Pre-increment operation++score[2]; // Pre-increment operationscore[4]++; // Post-increment operationscore[4]++; // Post-increment operation

Example:Example: PayArray.javaPayArray.java

Array elements can be used in relational operations:Array elements can be used in relational operations:if(cost[20] < cost[0])if(cost[20] < cost[0]){{

//statements//statements}}

They can be used as loop conditions:They can be used as loop conditions:while(value[count] != 0)while(value[count] != 0){{

//statements//statements}}

Page 8: Two Dimensional Arrays Found in chapter 8, Section 8.9

The Enhanced for LoopThe Enhanced for Loop Simplified array processing (read only)Simplified array processing (read only) Always goes through all elementsAlways goes through all elements General:General:

for(for(datatypedatatype elementVariableelementVariable : : arrayarray)) statement;statement;

Example:Example:int[] numbers = {3, 6, 9};int[] numbers = {3, 6, 9};For(int val : numbers)For(int val : numbers){{System.out.println(“The next value is” + val);System.out.println(“The next value is” + val);

} }

Page 9: Two Dimensional Arrays Found in chapter 8, Section 8.9

Array Methods & FieldsArray Methods & Fields

Arrays are objects and provide a public Arrays are objects and provide a public fieldfield named named length length that is a constant that can be that is a constant that can be tested.tested.double[] temperatures = new double[25];double[] temperatures = new double[25];

The length of an array can be obtained via The length of an array can be obtained via its length constant.its length constant.int size = temperatures.length;int size = temperatures.length;

– The variable The variable sizesize will contain 25. will contain 25.

Page 10: Two Dimensional Arrays Found in chapter 8, Section 8.9

Interesting Java featureInteresting Java feature It is possible to get the size of an array It is possible to get the size of an array

from a user:from a user:;;int numTests;int numTests;int[] tests;int[] tests;Scanner keyboard;Scanner keyboard;keyboard = new Scanner (System.in); keyboard = new Scanner (System.in); System.out.print("How many numbers do you have? ");System.out.print("How many numbers do you have? ");numTests = keyboard.nextInt();numTests = keyboard.nextInt();tests = new int[numTests];tests = new int[numTests];

Example: Example: DisplayTestScores.javaDisplayTestScores.java

Page 11: Two Dimensional Arrays Found in chapter 8, Section 8.9

Understanding Array ReferencesUnderstanding Array References

An array reference can be assigned to An array reference can be assigned to another array of the same type.another array of the same type.

// Create an array referenced by the numbers variable.// Create an array referenced by the numbers variable.int[] numbers = new int[10];int[] numbers = new int[10]; // Reassign numbers to a new array.// Reassign numbers to a new array.numbers = new int[5];numbers = new int[5];

Copying arraysCopying arrays– Wrong way Wrong way – Right wayRight way

Page 12: Two Dimensional Arrays Found in chapter 8, Section 8.9

Parameters & ArraysParameters & Arrays Passing single elementsPassing single elements

– PassElements.javaPassElements.java Passing entire arraysPassing entire arrays

– public static void showArray(int[] array)public static void showArray(int[] array)– PassArray.javaPassArray.java

Passing partially filled arraysPassing partially filled arrays Returning arraysReturning arrays

– public static double [ ] getArray() public static double [ ] getArray() – ReturnArray.javaReturnArray.java

Page 13: Two Dimensional Arrays Found in chapter 8, Section 8.9

Doing things with Arrays Doing things with Arrays Bad way Bad way Good wayGood way

– compare lengths (else they can’t be the same)compare lengths (else they can’t be the same)– then compare individual itemsthen compare individual items

Summing array elementsSumming array elements Finding the average of the array elementsFinding the average of the array elements Finding the minimum and maximum valueFinding the minimum and maximum value Searching arraysSearching arrays

– Sequential search – SearchArray.javaSequential search – SearchArray.java– Binary searchBinary search

Page 14: Two Dimensional Arrays Found in chapter 8, Section 8.9

Sorting an ArraySorting an Array

Java provides a class named Array that Java provides a class named Array that simplifies some array operations.simplifies some array operations.

The Array class has a static method named The Array class has a static method named sort that will sort a numeric array in sort that will sort a numeric array in ascending orderascending order..Array.sort(numbers);Array.sort(numbers);

To use the class, the import statement, To use the class, the import statement, import java.util.Array;import java.util.Array; must be used. must be used.

Page 15: Two Dimensional Arrays Found in chapter 8, Section 8.9

Other ArraysOther Arrays String ArraysString Arrays

– MonthDays.javaMonthDays.java– String objects have several methods.String objects have several methods.

toUpperCase,toUpperCase, compareTocompareTo equalsequals charAtcharAt

– Each element of a String array is a String object.Each element of a String array is a String object. String objects have a method String objects have a method named length()named length()

Arrays of ObjectsArrays of Objects– ObjectArray.javaObjectArray.java

Parallel arraysParallel arrays Two-Dimensional arraysTwo-Dimensional arrays

Page 16: Two Dimensional Arrays Found in chapter 8, Section 8.9

Two-Dimensional arraysTwo-Dimensional arrays Is an array of arraysIs an array of arrays Can be thought of as having rows and columnsCan be thought of as having rows and columns Declaring a two-dimensional array requires Declaring a two-dimensional array requires

two sets of brackets and two size two sets of brackets and two size declaratorsdeclarators– The first one is for the number of rowsThe first one is for the number of rows– The second one is for the number of columns.The second one is for the number of columns.

double[][] scores = new double[3][4];double[][] scores = new double[3][4];

Each array element has two subscriptsEach array element has two subscripts

Page 17: Two Dimensional Arrays Found in chapter 8, Section 8.9

Initializing and AccessingInitializing and Accessing Accessing two-dimensional array elementsAccessing two-dimensional array elements

– Can access individual elementsCan access individual elements– Can use a loop to access all elementsCan use a loop to access all elements

ExampleExample– CorpSales.javaCorpSales.java

Initializing a two-dimensional array requires enclosing Initializing a two-dimensional array requires enclosing each row’s initialization list in its own set of braces.each row’s initialization list in its own set of braces.int[][] numbers = {int[][] numbers = {{{1, 2, 31, 2, 3}}, , {{4, 5, 64, 5, 6}}, , {{7, 8, 97, 8, 9}}};};

Java automatically creates the array and fills its Java automatically creates the array and fills its elements with the initialization values.elements with the initialization values.– row 0 {1, 2, 3}row 0 {1, 2, 3}– row 1 {4, 5, 6}row 1 {4, 5, 6}– row 2 {7, 8, 9}row 2 {7, 8, 9}

Declares an array with three rows and three columns.Declares an array with three rows and three columns.

Page 18: Two Dimensional Arrays Found in chapter 8, Section 8.9

The length FieldThe length Field

Two-dimensional arrays are arrays of one-Two-dimensional arrays are arrays of one-dimensional arrays.dimensional arrays.

The length field of the array gives the number of The length field of the array gives the number of rows in the array. rows in the array.

Each row has a length constant tells how many Each row has a length constant tells how many columns is in that row.columns is in that row.

Each row can have a different number of columns.Each row can have a different number of columns. ExampleExample

– Lengths.javaLengths.java

Page 19: Two Dimensional Arrays Found in chapter 8, Section 8.9

Things to do with arraysThings to do with arrays Summing rowsSumming rows Summing columnsSumming columns Finding max valueFinding max value Finding min valueFinding min value Passing and returning arraysPassing and returning arrays

– There is no difference between passing a single or two-There is no difference between passing a single or two-dimensional array as an argument to a method.dimensional array as an argument to a method.

– The method must accept a two-dimensional array as a The method must accept a two-dimensional array as a parameter.parameter.

– Example: Example: Pass2Darray.javaPass2Darray.java

Page 20: Two Dimensional Arrays Found in chapter 8, Section 8.9
Page 21: Two Dimensional Arrays Found in chapter 8, Section 8.9