Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.

Slides:



Advertisements
Similar presentations
1 Arrays An array is a special kind of object that is used to store a collection of data. The data stored in an array must all be of the same type, whether.
Advertisements

Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
1 Various Methods of Populating Arrays Randomly generated integers.
Written by: Dr. JJ Shepherd
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Chapter 10.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Alice in Action with Java
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
1 4.3 Example: Volume of a Sphere Given the radius r, what is the weight of a ball (sphere) of wound twine?Given the radius r, what is the weight of a.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
JAVA Arrays. Objectives Be able to declare and initialize arrays Be able to conceptualize (draw) how arrays are represented in computer memory. Be able.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Java Programming: From Problem Analysis to Program Design, 4e
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Section 3 - Arrays and Methods. Arrays Array: collection of group of data variables of same type, sharing the same name for convenience - Easy to search.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Simple Methods Chap. 4 Study Sections 4.1 – 4.4 Writing Reusable Formulas.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Written by: Dr. JJ Shepherd
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
 2005 Pearson Education, Inc. All rights reserved Arrays.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter VII: Arrays.
Arrays Chapter 7.
Chapter 7 User-Defined Methods.
Java Primer 1: Types, Classes and Operators
Arrays Chapter 7.
How do you do the following?
Review for Midterm 3.
Presentation transcript:

Arrays Chap. 9 Storing Collections of Values 1

Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for student scores. (E. g., Mrs. White in §9.1) One Solution: Develop an assignment class that represents student scores on an assignment (e.g., a test or homework) and is able to print statistics for that assignment. 2

Preliminary Analysis 3 Different statistics require different capabilities: Average (arithmetic mean), max, min, range: _____________________ through the data needed to calculate these. Deviations (differences) from the mean, standard deviation: _________ passes needed— one to find average, one to find deviations. Median (requires sorting), mode: ____________ passes through the data needed.

4 How to proceed: Option 1: Enter the data as many times as necessary. Yuck! There must be a better way! Option 2: Put the data in a file on disk and read from the file as many times as necessary. Yes, this would work, but file I/O is slow (and we don't know how to do file I/O yet). Option 3: Store the data in an ______________ ____________: – –an ______________ – –a _______________ – –an ______________ – –a _______________

Behavior Our program should read the list of student names and assignment scores. It should then compute and display the average score and then the list of student names along with their deviations from the average. 5

Algorithm for program 6 1. Construct Keyboard object theKeyboard, Screen object theScreen, and Assignment object theAssignment. 2. Ask theAssignment to read the student info, displaying prompts on theScreen and reading input from theKeyboard. 3. Ask theAssignment to display the student names and statistics on theScreen. If we have an Assignment class that reads and stores the student names and scores, calculates the statistics (average and deviations), and displays the student names and statistics,the main program is easy:

Building the Assignment Class 7 ______________________________ : Constructor read() average() printStats() ______________________________ ): class size storage (array of strings) for names storage (array of doubles) for scores

8 import ann.easyio.*; class Assignment { public Assignment() { studentNames = null; studentScores = null; size = 0; } public double average() { int sum = 0; for (int i = 0; i < size; i++) sum += studentScores[i]; return (double)sum / size; } public void printStats(Screen theScreen) { double theAverage = average(); theScreen.println("\nThe average is: " + average()); theScreen.println("The standard deviations are:"); for (int i = 0; i < size; i++) theScreen.println(studentNames[i] + " " + studentScores[i] + " " + + (studentScores[i] - theAverage) ); } The Code

9 public void read(Screen theScreen, Keyboard theKeyboard) { theScreen.print("Enter the size of the class: "); size = theKeyboard.readInt(); if (size <= 0) { theScreen.println("invalid Assignment size: " + size); System.exit(-1); } else { studentNames = new String [size]; studentScores = new double [size]; } String name; theScreen.println("Enter the names and scores of "+ "the students in the class: "); for (int i = 0; i < size; i++) { theScreen.print((i + 1) + ": "); Keyboard.EatWhiteSpace(); studentNames[i] = (theKeyboard.readLine()); studentScores[i] = theKeyboard.readInt(); } private int size; private String [] studentNames; private double [] studentScores; } // end of class Assignment

10 class Teacher { public static void main(String [] args) { Screen theScreen = new Screen(); Keyboard theKeyboard = new Keyboard(); Assignment theAssignment = new Assignment(); theAssignment.read(theScreen, theKeyboard); theAssignment.printStats(theScreen); }

11 Sample run: Enter the size of the class: 3 Enter the names and scores of the students in the class: 1: Joe Blow 80 2: L. Nyhoff 100 3: Mary Doe 90 The average is: 90.0 The standard deviations are: Joe Blow L. Nyhoff Mary Doe

or assigned (the address of) an array created with ________ — Later array1 can be set to _______ e.g., see Assignment. Array Definitions 12 Java arrays are ___________  They must be accessed via ___________ Three declaration forms: 1.Uninitialized: Type [] arrayName; Example: ___________________ array1 ___________________

13 2. Using new operator Type [] arrayName = new Type [size]; where size is an integer-valued expression that specifies the number of elements in the array. Example: int size = theKeyboard.readInt(); // e.g, 4 ______________________________________ array2

14 Notes: A block of memory for the array is allocated _______________________. The ___________of this memory block is stored in the array variable; so an array variable is a ___________. Array elements are initialized with default values –________ for numeric types –________ for boolean –________ for reference types Array indexes are numbered beginning with ____. array2

15 3. Initialize with an array literal: Type [] arrayName = array-literal; where array-literal is a list of values of type Type enclosed in curly braces {} and separated by commas. Example: ________________________________________ array3 A block of memory of appropriate size is allocated and initialized with the listed values; address is stored in array3.

16 Arrays are ________________: array indexes are numbered beginning with 0. Elements of arrays of primitive types are stored as ___________; e.g. in Assignment : Array Properties [0][1][2]studentScores Elements of arrays of reference types are stored as ___________; e.g. in Assignment : [0][1][2] studentNames

The latest version of Java allows the use of array literals in the first form of array declaration Type [] arrayName = new Type [] array-literal; and also allows this expression to be used to assign a value to an array variable: arrayName = new Type [] array-literal; 17 Example: double [] array3 = ____________________________________; double [] array4;... array4 = new double [] {1.1, 2.2, 3.3, 4.4};

18 Each array has a public attribute ____________ whose value is the number of array elements. Example: For studentScores in our sample run, studentScores.length is ___. Each element of an array can be accessed by an expression of the form: arrayName[i] i is called an _______ or ___________ and may be any integer-valued expression. Typically a for loop is used to process array elements: for (int i = 0; i < ________________ ; i++) //... process ______________...

19 Examples: for (int i = 0; i < _______________________; i++) sum += studentScores[i]; for (int i = 0; i < studentScores.length; i++) theScreen.println(studentNames[i] + " " + studentScores[i] + " " + + (studentScores[i] - theAverage) ); for (int i = 0; i < studentScores.length; i++) { theScreen.print((i + 1) + ": "); Keyboard.EatWhiteSpace(); studentNames[i] = (theKeyboard.readLine()); studentScores[i] = theKeyboard.readInt(); }

for (int i = 0; i <= 4; i++) theScreen.println(array4[i]); // Line 42 Sample run: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at testprogram.main(testprogram.java:42) 20 Array indexes may not get ______________________; i.e., less than 0 or greater than array.length – 1. If they do, a fatal ArrayIndexOutOfBoundsException is thrown.

21 Arrays as parameters: The _____________________ of an array argument is passed to methods. Thus, as with class objects, modifying an array parameter will modify the corresponding array argument. public double average(______________ anArray) { double sum = 0; for (int i = 0; i < ___________________; i++) sum += anArray[i]; return sum / anArray.length; }... double [] a = {1.0, 2.0, 3.0}; theScreen.println("average: " + average(a) ); Note that average() can be used with a double array of any size. Not also the usefulness of the length attribute to determine an array's size.

22 Arrays as return values: Return type has the form ___________ ; a method defines a local array of this same type and returns it. (Actually, it's address/handle is returned.) public static _____________ readArray() { // declare theScreen and theKeyboard theScreen.print("Enter the size of the array: "); __________________ = new int[theKeyboard.readInt()]; theScreen.println("Enter the elements: "); for (int i = 0; i < anArray.length; i++) anArray[i] = theKeyboard.readInt(); return ______________; }... int [] a = readArray();

int [] original = {1, 2}; int [] copy1; copy1 = original; Copying Arrays: The same ___________________ as for other objects. int [] copy2; copy2 = (int[])original.clone(); 23 1 original[0] [1] copy1 2 copy2 [0] [1] 12 Changing copy1 changes original. Use String (inherited from class Object ) to produce a distinct copy.

– –anArray == anotherArray and anArray.equals(anotherArray) only check the handles of the two arrays. – –Special equality-checking methods must be written if more that this is needed. – –The String class has an equals() operator that checks string equality properly. 24 Array Equality: Same problem as for other objects:

The Vector Class + Vector s can ______ and _________. 25 Vector vec = new Vector(); int value; theScreen.println("enter values: "); for (;;){ value = theKeyboard.readInt(); if (value == -1) break; vec.addElement(new Integer(value)); } Also... -Vector elements must be ________ __  types of numeric elements must be wrapper classes  many conversions between wrapper classes and primitive types

int sum = 0; for (int i = 0; i < vec.size(); i++) sum += ((Integer)(vec.elementAt(i))).intValue(); theScreen.println("sum: " + sum); 26 A better alternative: ArrayList (chap. 12) - Parameters and return type of Vector methods are of type ___________  typecasts must be used to convert to/from element type; also...

Problem: To store student scores for more than one assignment.Problem: To store student scores for more than one assignment. One Solution: Develop a program that can store scores for multiple students for multiple assignments, and, given the index of the student and the assignment number, display the appropriate score.One Solution: Develop a program that can store scores for multiple students for multiple assignments, and, given the index of the student and the assignment number, display the appropriate score. 27 Multidimensional Arrays

The data structure required here could definitely use some sort of an array, but would be hard to fit into a one- dimensional array.The data structure required here could definitely use some sort of an array, but would be hard to fit into a one- dimensional array. Most languages provide multi-dimensional arrays for this sort of problem.Most languages provide multi-dimensional arrays for this sort of problem. 28 Preliminary Analysis

We can view a two-dimensional array as an _________________; that is, a one-dimensional array whose elements are __________________________. For example: ___________________ = { { 10, 17, 10, 18, 12 }, { 20, 18, 14, 19, 19 }, { 10, 14, 10, 14, 10 }, { 15, 15, 15, 15, 15 }, { 20, 19, 18, 17, 16 }, { 20, 20, 19, 20, 20 } }; 29 ___________ Storage is ___________ : Each internal _______ array literal is a _______ of grades.

Accessing Array Elements [0] [1] [2] [3] [4] [0] [1] [2] [3] [4] [5] 30 grades[1] = grades[1][3] = ______ grades[3][1] = ______ grades[0] = ____________________ __________ of grades

Output: for (int row=0; row < ____________________ ; row++) { for (int col=0; col < ___________________________ ; col++) theScreen.print( _________________________ + "\t"); theScreen.println(); }