1 Lecture 6 Objects for Organizing Data Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.

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

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Chapter 10 Introduction to Arrays
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
Arrays.
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 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
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 Modelling 1-D Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing Array.
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”
Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
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.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with 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.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
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.
The Interdisciplinary Center, Herzelia Lecture 5, Introduction to CS - Information Technologies Slide #1 More Programming Constructs -- Introduction In.
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
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.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
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.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
Dr. Sahar Shabanah Lecture 3: Arrays. Data Structures Data structures are organized collections of information and a set of operations used to manage.
© 2004 Pearson Addison-Wesley. All rights reserved October 15, 2007 Searching ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
1 Sorting b Sorting is the process of arranging a list of items into a particular order b There must be some value on which the order is based b There.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Java Software Solutions Lewis and Loftus Chapter 3 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Program Elements -- Introduction.
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:
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
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.
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.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
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.
Lecture 6 Objects for Organizing Data
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 in Java.
Visual Programming COMP-315
Outline Creating Objects The String Class The Random and Math Classes
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
Arrays.
Presentation transcript:

1 Lecture 6 Objects for Organizing Data Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology

1 Outline array declaration and use arrays of objects parameters and arrays multidimensional arrays the Vector class additional techniques for managing strings

2 Arrays An array is an ordered list of values Each value has a numeric index An array of size N is indexed from zero to N-1 The following array of integers has a size of 10 and is indexed from 0 to scores

3 Arrays Array reference: scores[4] – the 5th value in the array –refers to the value 67 It can be assigned a value, printed, used in a calculation

4 Arrays An array stores multiple values of the same type That type can be primitive types or objects We can create an array of integers, or an array of characters, or an array of String objects, etc. Array is an object The name of the array is a object reference variable, and the array itself is instantiated separately

5 Declaring Arrays The scores array could be declared as follows: int[] scores = new int[10]; –Type: int[] (an array of integers) –Size: 10 (array of 10 integers) Unknown size: a handle to an array object int[] scores;

6 Declaring Arrays Some examples of array declarations: float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750];

7 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, they must be in bounds (0 to N-1) The Java interpreter will throw an exception if an array index is out of bounds This is called automatic bounds checking Its common to inadvertently introduce off-by-one errors when using arrays

8 Bounds Checking Each array object has a public constant called length that stores the size of the array It is referenced through the array name (just like any other object): scores.length Note that length holds the number of elements, not the largest index See Reverse_Numbers.java and Adjust_Test_Scores.java

9 Array Declarations Revisited Array declarations: two ways float[] prices; and float prices[]; are essentially equivalent The first format is usually more readable

10 Initializer Lists An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Examples: char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}; int[] primes = {2, 3, 5, 7, 11, 13, 17, 19};

11 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 only be used in the declaration of an array

12 Arrays of Objects The elements of an array can be object references The declaration String[] words = new String[25]; reserves space to store 25 references to String objects It does NOT create the String objects themselves Each object stored in an array must be instantiated separately

13 Arrays of Objects Objects can have arrays as instance variables Fairly complex structures can be created simply with arrays and objects See RollCall.java (next 4 pages)

class RollCall { public static void main (String[] args) { Membership roster = new Membership(); Member person; System.out.println(); person = roster.findMember(26911); if (person == null) System.out.println ("No match found"); else { System.out.println (”Found the following member:"); person.print(); } System.out.println(); roster.print(); } // method main } // class RollCall

class Membership { private Member[] memberList; public Membership() { memberList = new Member[4]; memberList[0] = new Member ("Johnny Storm", 70469); memberList[1] = new Member ("Sue Richards", 69048); memberList[2] = new Member ("Reed Richards", 26911); memberList[3] = new Member ("Ben Grimm", 89696); } // constructor Membership public Member findMember (int target) { int index = 0; while (index < memberList.length) { if (memberList[index].getMembershipNumber() == target) return memberList[index]; index++; } return null; }

public Member findMember (int target) { int index = 0; while (index < memberList.length) { if (memberList[index].getMembershipNumber() == target) return memberList[index]; index++; } return null; } // method findMember public void print() { System.out.println ("Member\t\tId #"); for (int person=0; person < memberList.length; person++) memberList[person].print(); } // method print } // class Membership

class Member { private String name; private int membershipNumber; public Member (String memberName, int idNumber) { name = memberName; membershipNumber = idNumber; } // constructor Member public int getMembershipNumber() { return membershipNumber; } // method getMembershipNumber public void print() { System.out.println (name + "\t" + membershipNumber); } // method print } // class Member

14 Arrays as Parameters An entire array can be passed to a method as a parameter The reference to the array is passed, making the formal and actual parameters aliases of each other Changing an array element in the method changes the original An array element can be passed to a method as well, and follow the parameter passing rules of that element's type See Array_Test.java

15 Multidimensional Arrays A one-dimensional array stores a simple list of values A two-dimensional array can be thought of as a table of values, with rows and columns A two-dimensional array element is referenced using two index values A two-dimensional array in Java is an array of arrays, therefore each row can have a different length

16 Multidimensional Arrays An initializer list can be used to create and set up a multidimensional array Note that each array dimension has its own length constant See MultiArrayTest.java (Next page) See Class MultiArray

class MultiArrayTest { public static void main (String[] args) { MultiArray chart = new MultiArray(); chart.print(); System.out.println(); for (int column=0; column < 4; column++) System.out.println ("Sum of column " + column + ": " + chart.sumColumn (column)); } // method main } // class MultiArrayTest

class MultiArray { int[][] table = { {28, 84, 47, 72}, {69, 26}, {91, 40, 28}, {42, 34, 37}, {13, 26, 57, 35} }; public void print() { for (int row=0; row < table.length; row++) { for (int column=0; column < table[row].length; column++) System.out.print (table[row][column] + " "); System.out.println(); } } // method print public int sumColumn (int column) { int sum = 0; for (int row=0; row < table.length; row++) if (column < table[row].length) sum += table[row][column]; return sum; } // method sumColumn } // class MultiArray

class Soda_Scores { private final int RESPONDENTS = 10; private final int SODAS = 4; private int[][] results = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4}, {2, 4, 3, 4, 3, 3, 2, 1, 2, 2}, {3, 5, 4, 5, 5, 3, 2, 5, 5, 5}, {1, 1, 1, 3, 1, 2, 1, 3, 2, 4} }; public int num_sodas() { return SODAS; } public boolean worthy (int soda, int level) { int count = 0; for (int person=0; person < results[soda].length; person++) if (results[soda][person] >= level) count++; return (count > RESPONDENTS/2); } // method worthy } // class Soda_Scores What is wrong with this class?

The Vector Class An object of class Vector is similar to an array in that it stores multiple values However, a vector –only stores objects –does not have the indexing syntax that arrays have Service methods are used to interact with a vector The Vector class is part of the java.util package See Beatles.java (next page)

import java.util.Vector; class Beatles { public static void main (String[] args) { Vector band = new Vector(); band.addElement ("Paul"); band.addElement ("Pete"); band.addElement ("John"); band.addElement ("George"); System.out.println (band); band.removeElement ("Pete"); band.addElement ("Ringo"); System.out.println (band); } // method main } // class Beatles

The Vector Class An important difference between an array and a vector is that a vector can change its size as needed. Each vector initially has a certain amount of memory space reserved for storing elements If an element is added that doesn't fit in the existing space, more room is automatically acquired

19 The Vector Class A vector is implemented using an array Whenever new space is required, a new, larger array is created, and the values are copied from the original to the new array To insert an element, existing elements are first copied, one by one, to another position in the array Therefore, the implementation of Vector in the API is not very efficient See ZZ_Top.java (Next)

import java.util.Vector; // page 825 class ZZ_Top { public static void main (String[] args) { Vector song = new Vector(); String name = new String ("ZZ Top's Greatest Hits"); Integer track = new Integer (6); String title = "Cheap Sunglasses"; Double price = new Double (15.95); Vector authors = new Vector (2); authors.addElement ("Gibbons"); authors.addElement ("Hill"); song.addElement (track); song.addElement (title); song.addElement (authors); song.addElement (price); song.insertElementAt (name, 0);

System.out.println (song); authors.addElement ("George"); System.out.println (song); System.out.println ("song size: " + song.size()); System.out.println ("authors size: " + authors.size()); System.out.println ("song begins: " + song.firstElement()); System.out.println ("authors begins: " + authors.firstElement()); System.out.println ("song ends: " + song.lastElement()); System.out.println ("authors ends: " + authors.lastElement()); authors.setElementAt ("Frank", authors.indexOf ("George")); System.out.println (song); song.removeAllElements(); System.out.println (song); } // method main } // class ZZ_Top

The StringTokenizer Class Revisited We've seen a StringTokenizer object separate a string into separate tokens By default, those tokens are delimited by white space By using other StringTokenizer constructors, we can define the delimiters used to define a token We can also set whether we want the delimiters themselves returned as tokens See Voltaire.java and URL_Tokens.java

import java.util.StringTokenizer; // page 805 public class Voltaire { public static void main (String[] args) { String quote = "Use, do not abuse; neither abstinence " + "nor excess renders a man happy."; StringTokenizer words = new StringTokenizer (quote); System.out.println ("Characters: " + quote.length()); System.out.println ("Tokens: " + words.countTokens()); while (words.hasMoreTokens()) { System.out.println (words.nextToken()); } } // method main } // class Voltaire

class URL_Tokenizer { private String protocol; private String address; private String resource; public URL_Tokenizer (String URL_Text) { StringTokenizer URL = new StringTokenizer (URL_Text, ":"); protocol = URL.nextToken(); address = URL.nextToken (":/"); resource = URL.nextToken (""); } // constructor URL_Tokenizer public String get_protocol() { return protocol; } public String get_address() { return address; } public String get_resource() { return resource; } } // class URL_Tokenizer … URL_Tokenizer url = new URL_Tokenizer (" // main

The StringBuffer Class Recall that the value of a String object is immutable; once set it cannot be changed The StringBuffer class can be used to define a character string whose value can change It's service methods include the ability to append and insert characters See Money.java However, most functionality defined by the StringBuffer class can be accomplished with String objects and string concatenation

public class Money { public static void main (String[] args) { StringBuffer text1 = new StringBuffer(); // page 803 StringBuffer text2 = new StringBuffer(" m"); StringBuffer text3 = new StringBuffer ("1 dollar"); text1.append (1); text1.append (" p"); text1.append ('e'); text1.append ('n'); text1.append ("ny"); text2.insert (0, 1); text2.insert (2, "di"); text2.insert (5, 'e'); System.out.println (text1); System.out.println (text2); System.out.println (text3); text3.reverse(); System.out.println (text3); } // method main} // class Money

Conclusion Java Array is an object. Array size of N: index 0 to N-1 Bounds checking Mutlidimensional array ==> array of arrays each element could have a different length. Vector (similar to Array) can dynamically change size StringTokenizer class (good for compiler and other app. StringBuffer class