8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.

Slides:



Advertisements
Similar presentations
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Advertisements

Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
Arrays Clark Savage Turner, J.D., Ph.D. Copyright © 2000 by C Scheftic. All rights reserved. These notes do rely heavily.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
© 2006 Pearson Addison-Wesley. All rights reserved2-1 Console Input Using the Scanner Class Starting with version 5.0, Java includes a class for doing.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 6: Arrays Java Software Solutions Third Edition
Unit 5 1 Arrays and Vectors H Arrays and vectors are objects that help us organize large amounts of information H We will talk about: array declaration.
Chapter 2 Section 2.2 Console Input Using The Scanner CLASS Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
1 Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 7: Arrays.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 7 Arrays: Part 1 of 2. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of.
Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split()
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
Chapter 2: Data and Expressions String and String Concatenation Escape Sequences Variables Primitive Date Types Expressions Interactive Programs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Interactive Programs Programs that get input from the user 1 In PowerPoint, click on the speaker icon then click the "Play" button to hear the narration.
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
Arrays. Arrays are objects that help us organize large amounts of information.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Arrays in Java.
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Outline Declaring and Using Arrays Arrays of Objects
Arrays.
Presentation transcript:

8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds checking and capacity –Two dimensional array –arrays that store object references –Pitfall: Scanner class, nextLine method (Not in the textbook)

8-2 Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9

8-3 Declaring Arrays The scores array could be declared as follows: int[] scores = new int[10]; The type of the variable scores is int[] (an array of integers) The reference variable scores is set to a new array object that can hold 10 integers

8-4 Declaring and Using Arrays Some other examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

8-5 Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] refers to the value 94 (the 3rd value in the array)

8-6 Arrays scores[2] The expression represents a place to store a single integer and can be used wherever an integer variable can be used

8-7 Arrays For example, an array element can be assigned a value, printed, or used in a calculation : scores[2] = 89; scores[0] = scores[0] + 2; System.out.println ("Top = " + scores[5]);

8-8 Arrays The values held in an array are called array elements - An array stores multiple values of the same type – the element type The element type can be a primitive type or an object reference Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc.

8-9 Arrays In Java, the array itself is an object that must be instantiated Another way to picture the scores array: scores

8-10 BasicArray.java public class BasicArray { // // Creates an array, fills it with various integer values, // modifies one value, then prints them out. // public static void main (String[] args) { final int LIMIT = 15, MULTIPLE = 10; int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value for (int index = 0; index < LIMIT; index++) System.out.println(list[index]); } }

8-11 Exercise Write a program to declare an array named nums of ten elements of type int and initialize the elements (starting with the first) to the values 2, 4, 6, 8,..., 18, 20 respectively.

8-12 Array Index and Bounds Checking

8-13 Array Index and Bounds Checking Once an array is created, it has a fixed size An index used in an array reference must specify a valid element. That is, the index value must be in range 0 to N-1 The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds This is called automatic bounds checking Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

8-14 Bounds Checking For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 The following reference will cause an exception to be thrown: for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; problem Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

8-15 Bounds Checking Each array object has a public constant called length that stores the size of the array It is referenced using the array name: scores.length Note that length holds the number of elements, not the largest index

8-16 ReverseOrder.java public static void main (String[] args) { Scanner scan = new Scanner (System.in); double[] numbers = new double[10]; System.out.println ("The size of the array: " + numbers.length); for (int index = 0; index < numbers.length; index++) { System.out.print ("Enter number " + (index+1) + ": "); numbers[index] = scan.nextDouble(); } System.out.println ("The numbers in reverse order:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " "); }

8-17 Exercise Assume that an array of integers named arr has been declared and initialized. Write a single statement that assigns a new value to the first element of the array. The new value should be equal to twice the value stored in the last element of the array.

8-18 Initializer Lists

8-19 Initializer Lists An initializer list can be used to instantiate and fill an array in one step The values are delimited by braces and separated by commas Examples: int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};

8-20 Initializer Lists Note that when an initializer list is used: –the new operator is not used –no size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can be used only in the array declaration

8-21 Two dimensional Array

8-22 Two-Dimensional Arrays A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions Copyright © 2012 Pearson Education, Inc.

8-23 Two-Dimensional Arrays To be precise, in Java a two-dimensional array is an array of arrays A two-dimensional array is declared by specifying the size of each dimension separately: int[][] table = new int[12][50];

8-24 Two-Dimensional Arrays A array element is referenced using two index values: value = table[3][6] The array stored in one row can be specified using one index table[3]: the array of elements table[3][0], table[3][1], …, table[3][49]

8-25 Two-Dimensional Arrays Copyright © 2012 Pearson Education, Inc. ExpressionTypeDescription tableint[][] 2D array of integers, or array of integer arrays table[5]int[] array of integers table[5][2]int integer

8-26 //******************************************************************** // TwoDArray.java Author: Lewis/Loftus // // Demonstrates the use of a two-dimensional array. //******************************************************************** public class TwoDArray { // // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. // public static void main (String[] args) { int[][] table = new int[5][10]; // Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table for (int row=0; row < table.length; row++) { for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); }

8-27 Exercise Write a program that store the values of multiplication table from 1 to 9 in a 2D array and display the numbers.

8-28 Array of Objects

8-29 Arrays of Objects The elements of an array can be object references The following declaration reserves space to store 5 references to String objects String[] words = new String[5];

8-30 Arrays of Objects String[] words = new String[5]; It does NOT create the String objects themselves Initially an array of objects holds null references Each object stored in an array must be instantiated separately

8-31 Arrays of Objects The words array when initially declared: words At this point, the following reference would throw a NullPointerException : System.out.println (words[0]);

8-32 Arrays of Objects After some String objects are created and stored in the array: “friendship” words - - “loyalty” “honor”

8-33 Arrays of Objects Keep in mind that String objects can be created using literals The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep"};

8-34 Exercise Write a program that simulates shuffling a deck of 52 cards.

8-35 Pitfall: Scanner Class, nextLine method

8-36 Pitfall: Scanner Class, nextLine method Scanner, nextLine method: –Reads the remainder of a line of text and returns as a string. –Starting whenever the last keyboard reading left off –The line terminator '\n' is read and discarded, not included in the string returned. int number = scan.nextInt(); String str1 = scan.nextLine(); String str2 = scan.nextLine();

8-37 Pitfall: Scanner Class, nextLine method Pitall: calling nextLine after next, nextInt, nextDouble method –next, nextInt, or nextDouble reads the input but does not read the end-of-line ('\n') character. So the nextLine invocation after reads the rest of the line, which is nothing other than '\n' and returns the empty string.

8-38 Pitfall: Scanner Class, nextLine method Fix the problem: –Include an extra inovation of nextLine method when combining next, nextInt, or nextDouble with nextLine method for reading from the keyboard int number = scan.nextInt(); scan.nextLine(); String str1 = scan.nextLine(); String str2 = scan.nextLine();

8-39 Readings and Assignments Reading: Chapter , 8.6 Lab Assignment: Java Lab 6 Self-Assessment Exercises: –Self-Review Questions Section SR 8.3, 8.10, 8.11, 8.15 –After Chapter Exercises EX 8.1, 8.4, 8.5 a, b, 8.7, 8.8