CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 7: Oct 3-7, 2011 Aditya Mathur Department of Computer Science Purdue University.

Slides:



Advertisements
Similar presentations
SOPH 303 The Digital World Term 3 Spring 2013 Notes for Week 1. Sessions 2 and 3 Revised: January 28, 2013 Aditya Mathur Head of Pillar Information Systems.
Advertisements

CS 180 Problem Solving and Object Oriented Programming Spring 2011 February 16, 2011 Aditya Mathur Department of Computer Science Purdue University West.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 2: August 29-September 2, 2011 Aditya Mathur Department of Computer Science.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 8: Oct 10-14, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 4: September 12-16, 2011 Aditya Mathur/Tim Korb Department of Computer.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 13: Nov 15-19, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 9: Oct 17-21, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for the Final Lecture Dec 7, 2011 Aditya Mathur Department of Computer Science Purdue.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 3: September 5-9, 2011 Aditya Mathur Department of Computer Science Purdue.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
CS 106 Introduction to Computer Science I 02 / 20 / 2008 Instructor: Michael Eckmann.
C++ for Engineers and Scientists Third Edition
1 Lab Session-III CSIT-120 Spring 2001 Revising Previous session Data input and output While loop Exercise Limits and Bounds GOTO SLIDE 13 Lab session.
Java Coding David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 7: Oct 4-8, 2010 Aditya Mathur Department of Computer Science Purdue University.
CPS 2231 Computer Organization and Programming Instructor: Tian (Tina) Tian.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 11: Oct 31-Nov 4, 2011 Aditya Mathur Department of Computer Science Purdue.
Java Building Elements Lecture 2 Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 3: September 6-10, 2010 Aditya Mathur Department of Computer Science Purdue.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
CPS120: Introduction to Computer Science
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.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Flow of Control Part 1: Selection
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Fundamental Programming: Fundamental Programming Introduction to C++
Visual Basic Programming
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
COMP Primitive and Class Types Yi Hong May 14, 2015.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 11: Nov 1-5, 2010 Aditya Mathur Department of Computer Science Purdue University.
CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 14: Nov 21-25, 2011 Aditya Mathur Department of Computer Science Purdue.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
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.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 9: Oct 18-22, 2010 Aditya Mathur Department of Computer Science Purdue.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 6: September 27-Oct 1, 2010 Aditya Mathur Department of Computer Science.
IAS 1313: OBJECT ORIENTED PROGRAMMING Week 3: Data Type, Control Structure and Array Prepared by: Mrs Sivabalan1.
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
Yanal Alahmad Java Workshop Yanal Alahmad
Advanced Programming Behnam Hatami Fall 2017.
CS 177 Week 15 Recitation Slides
Arrays, For loop While loop Do while loop
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
elementary programming
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
CS Problem Solving and Object Oriented Programming Spring 2019
CS Problem Solving and Object Oriented Programming Spring 2019
CS Problem Solving and Object Oriented Programming Spring 2019
CS Problem Solving and Object Oriented Programming Spring 2019
CS Problem Solving and Object Oriented Programming Spring 2019
Presentation transcript:

CS 180 Problem Solving and Object Oriented Programming Fall 2011 Notes for Week 7: Oct 3-7, 2011 Aditya Mathur Department of Computer Science Purdue University West Lafayette, IN, USA 1.Review 2.Arrays 3.Demo 4.Multi-dimensional arrays 5.Visual depiction of arrays 10/4 This Week:

Review 2©Aditya Mathur. CS 180. Fall Week 710/5/2011

The edit, compile, execute cycle 3©Aditya Mathur. CS 180. Fall Week 710/5/2011 Edit a Java program Compile your program Execute your program Syntax Error Run time Error or Incorrect Output No syntax error Correct program.java file(s).class file(s) (byte code)

Classes and Objects 4©Aditya Mathur. CS 180. Fall Week 710/5/2011 Set of real or virtual objects animal vehicle student flower Class AnimalClass VehicleClass StudentClass Flower Template in Java dog Class DogmyDogmarysDog Objects created truckstudent RepresentCreate

String 5©Aditya Mathur. CS 180. Fall Week 710/5/2011 Is a sequence of zero or more Unicode characters. Examples: “Greetings!” “Your total tax is:” “Please enter the price:” “ “” Declaration: String name=“Beatles”; // name is an object of type String String store=“Macy’s”; // store is an object of type String

String 6©Aditya Mathur. CS 180. Fall Week 710/5/2011 Expressions: String firstName, middleInitial, lastName; String fullName; fullName=firstName+middleInitial+lastName; String message=“Please enter the price:”;

Strings: Other operations You may apply a variety of operations to strings. Examples follow. 7©Aditya Mathur. CS 180. Fall Week 710/5/2011 StatementOperation used String commend=“Bently,”+ “ good girl!”;Catenation char firstChar=commend.charAt(0);Character extraction movieName.equals(“Fugitive”)Comparison String.valueOf(29)Conversion to String commend.charAt(5)Extract character at position 5 from string commend commend.replace(“Bently”, “Ziggy”);Replace “Bently” by “Ziggy” commend.substring(startIndex, endIndex);Extract substring of characters starting from position startIndex until and including position endIndex-1.

Types 8©Aditya Mathur. CS 180. Fall Week 710/5/2011

Types 9©Aditya Mathur. CS 180. Fall Week 710/5/2011 Set of valuesSet of Operations x x x x x a b c

Primitive types: short, int, long 10©Aditya Mathur. CS 180. Fall Week 710/5/ Set of integersSet of Operations * % Integer.MAX_VALUE: Integer.MIN_VALUE: Long.MAX_VALUE: Long.MIN_VALUE: short: 2 bytes int: 4 bytes long: 8 bytes

Primitive types: short, int, long: Examples 11©Aditya Mathur. CS 180. Fall Week 710/5/2011 Real world entity or expressionTypePossible name in Java Population of a countryintcountryPopulation Age of a patient (in years)shortpatientAge Number of different ways to arrange 15 books in a bookshelf longbookArrangementCount Difference between two integersint or long diff Number of web siteslongnumberOfWebSites

Primitive types: float, double 12©Aditya Mathur. CS 180. Fall Week 710/5/ Set of integersSet of Operations (sample) * > Float.MAX_VALUE: e+38fFloat.MIN_VALUE: e-45f Double.MAX_VALUE: e+308 Double.MIN_VALUE: e E4 == Infinity -Infinity NaN float: 4 bytes double: 8 bytes

Primitive types: float, double: Examples 13©Aditya Mathur. CS 180. Fall Week 710/5/2011 Real world entity or expressionTypePossible name in a Java program Height of a personfloatheight Voting percentagefloatvotePercent Wavelength of green lightdoublewavelengthLIght Price of a ticketfloatticketPrice πdoublepi (Note: PI is a constant in Java)

Primitive types: boolean 14©Aditya Mathur. CS 180. Fall Week 710/5/2011 Set of logical valuesSet of Operations (sample) != == true false || && | boolean: 1 bit; size not defined

Primitive types: boolean: Examples 15©Aditya Mathur. CS 180. Fall Week 710/5/2011 Real world entity or expressionTypePossible name in a Java program Value of x<y;booleanresult she/he drives a carbooleancanDriveCar Class endedbooleanclassEnded

Primitive types: char 16©Aditya Mathur. CS 180. Fall Week 710/5/2011 Set of characters (sample values shown) Set of Operations (sample) != == ‘a’ ‘&’ || && | ‘$’ ‘+’ char: 2 bytes, unicode character

Primitive types: char: Examples 17©Aditya Mathur. CS 180. Fall Week 710/5/2011 Real world entity or expressionTypePossible name in a Java program Middle initialcharmiddleInitial Letter of the alphabetcharletter US currency signcharusCurrency

Names 18©Aditya Mathur. CS 180. Fall Week 710/5/2011 Used to denote classes, objects, data Contain characters; must start with a letter, or a $ sign or an underscore. Examples: height, area1, Dog, $great Length unlimited, case sensitive. Dog and dog are different names. Convention: All class names begin with an uppercase letter; all other names begin with a lower case letter.

Constants 19©Aditya Mathur. CS 180. Fall Week 710/5/2011 A constant is something that cannot change during program execution. Examples: Integer constants: 0, 1, -1, +24, 29, , O14, 0x1B Floating point constants: 0.0, e28, Boolean constants: true, false Character constants: ‘ ‘, ‘a’, ‘A’, ‘$’ String constants: “”, “ “, “Hi!”, “Alice in Wonderland”

Named Constants 20©Aditya Mathur. CS 180. Fall Week 710/5/2011 A constant can be named and the name used instead of the constant itself. Examples: final float pi= ; final boolean dogsExist=true;

Variables 21©Aditya Mathur. CS 180. Fall Week 710/5/2011 A variable is something whose value may change during program execution. Every variable has a name and a type. Every variable must be declared before it is used.

Declarations 22©Aditya Mathur. CS 180. Fall Week 710/5/2011 int age; float height, area; String name; boolean lightsOn; int x=1, y=0; String firstName=“Harry”;

Simple expressions 23©Aditya Mathur. CS 180. Fall Week 710/5/2011 Expressions are used to compute “something”. float x, y, z; x*y+z; // Arithmetic expression, results in float value x<y; // Boolean expression, results in boolean value String firstName=“Mary”, lastName= “Jones”; firstName+” “+lastName; // Results in a string

Assignment statement 24©Aditya Mathur. CS 180. Fall Week 710/5/2011 An assignment statement allows assigning the value of an expression to a variable. float p=x*y+z; // p gets the value of x*y+z boolean q=x<y; // q gets the value of x<y String firstName=“Mary”, lastName= “Jones”; String name= firstName+” “+lastName;

Handling characters 25©Aditya Mathur. CS 180. Fall Week 710/5/2011 char first=‘a’; char second=‘b’; Compare the values of two character variables: Yes if(first==second) NO if(first.equals(second)) Extract a character from a string: String course=“CS180”; char c=course.charAt(pos); // Extracts the character at position pos

Mixing Strings and characters 26©Aditya Mathur. CS 180. Fall Week 710/5/2011 char first=‘a’; String s1=“b”; The following are correct: String s2=first+s1; System.out.println(first+s1); Following are not correct: if (s1==first) if(s1.equals(first)) if(first.equals(s1))

Readings and Exercises for Week 7 Readings: Chapter 7: 7.1, 7.2, 7.3, 7.4 Self help exercises: 7.3, 7.4, 7.5, 7.7 [Optional] 10/5/2011©Aditya Mathur. CS 180. Fall Week 727

Arrays 10/5/2011©Aditya Mathur. CS 180. Fall Week 728

Arrays: What are these? 10/5/2011 A homogeneous collection of variables or objects. All elements of an array are of the same type. Examples: Array of integers where each integer represents the age of a patient. Array of cars where each element of the array denotes a specific car. Array of flowers where each element of the array denotes a flower. ©Aditya Mathur. CS 180. Fall Week 729

Arrays: When to use? 10/5/2011 When there is a need to retain data in memory for efficient processing. Data is created once and used many times. Examples: Array of flights: Search for a specific flight Array of cars: Search for a specific car, or find the average price. Array of laptops: find the cheapest laptop ©Aditya Mathur. CS 180. Fall Week 730

Declaring an Array 10/5/2011 int [] age; /* age refers to an array of integers; e.g. age of people in a database*/ double [] weight; /* weight refers to an array of doubles; e.g. weights of items shipped*/ String [] name; /* name refers to an array of elements each of type String; e.g., names of people in a database*/ Indicates age is an array variable ©Aditya Mathur. CS 180. Fall Week 731

Declaring an Array of objects 10/5/2011 Bird [] bird; /* Bird refers to a class; bird is an array where each element is an object of type Bird. */ Aircraft [] fleet; /* Aircraft refers to a class; fleet is an array where each element is an object of type Aircraft. */ ©Aditya Mathur. CS 180. Fall Week 732

Creating an Array 10/5/2011 int [] age=new int[10]; /* age is an array of 10 elements each of type int*/ double [] weight=new double[100]; /* weight is an array of 100 elements each of type double*/ String [] name=new String[15]; /* name is an array of 15 elements each of type String*/ Aircraft [] fleet=new Aircraft[150]; /* fleet is an array of 150 elements each of type Aircraft*/ ©Aditya Mathur. CS 180. Fall Week 733

Single dimensional array: Example 1 10/5/2011 int [] cloudyDays=new int [12] // average cloudy days/month ©Aditya Mathur. CS 180. Fall Week 734 Anchorage, Alaska [ ] cloudyDays[0]cloudyDays[5]cloudyDays[11] Index Data

Single dimensional array: Example 2: Declaration 10/5/2011 Car [] carStock=new Car [5] // Cars at a dealership ©Aditya Mathur. CS 180. Fall Week 735 public class Car{ String make; // e.g., Ford String model; // e.g., Fusion int year; // e.g., 2011 long msrp; // e.g., US$23,145 Picture carPic; }

Single dimensional array: Example 2: Visual 10/5/2011 Car [] carStock=new Car[5] // Cars at a dealership ©Aditya Mathur. CS 180. Fall Week 736 CS180 Dealership in West Lafayette [ ] carStock[0] carStock[4] Index Object Reference {Porsche, Boxster Spyder, 2011, 72000, } } {Ford, fusion, 2011, } ….

Accessing an array element: general syntax 10/5/2011 name [expression] Index, starts from 0, must be an intName of the array Examples: age[i]; // 0<=i<10 fleet[k]; // 0<=k<150 weight[i+j]; // 0<=(i+j)<100 Note: First element of an array is located at index 0. ©Aditya Mathur. CS 180. Fall Week 737

Accessing an array element 10/5/2011 int [] age=new int[10]; int p= age[5]; /* p gets element at index 5 of array age*/ double [] weight=new double[100]; double hisWeight=weight[i]; /* hisWeight gets the element of weight at index i*/ Aircraft [] fleet=new Aircraft[150]; Aircraft rental=fleet[k]/* rental gets the element of fleet located at index k */ ©Aditya Mathur. CS 180. Fall Week 738

Assigning a value to an array element 10/5/2011 int [] age=new int[10]; age[i]=15; /* (i+1) th element of age becomes 15. */ double [] weight=new double[100]; weight[k]=weight[k]-10; /* (k+1) th element of the weight is decremented by 10.*/ Aircraft [] fleet=new Aircraft[150]; fleet[i]=new Aircraft(); /* (i+1) th element of fleet gets a new Aircraft */ int [] age={-15, 20, 30} // All elements initialized ©Aditya Mathur. CS 180. Fall Week 739

Iterating through elements of an array 10/5/2011 In many problems we need to iterate through all or a few of the elements of an array. Such an iteration is accomplished by using a for or a while loop. ©Aditya Mathur. CS 180. Fall Week 740

Announcements 1.Feast with Faculty: Today at 6:30pm. Ford Dining Hall. 1.Next week:. Class does not meet Monday and Wednesday.. No lab sessions... Recitations WILL MEET 2.Exam 1 grades should be on the blackboard by Sunday afternoon. 10/5/2011©Aditya Mathur. CS 180. Fall Week 741

Commonly used syntax of the for statement 10/5/2011 for( init; condition; increment){ Loop body; i.e., a sequence of statements. } ©Aditya Mathur. CS 180. Fall Week 742 Executed once prior to entering the loop Checked each time prior to entering the loop body; loop terminates if condition is false Executed at the end of each iteration

Problem 1: Initialize an array of elements 10/5/2011 // Initialize an array of n elements to random numbers // between 0 and 1. final int n=100;// Array size double [] rnum=new double [n]; // Create array to hold numbers for( int i=0; i<n; i++){ rnum[i]=Math.random() // Initialize the ith element } // End of for ©Aditya Mathur. CS 180. Fall Week 743

Problem 2: Initialize an array (read from console) 10/5/2011©Aditya Mathur. CS 180. Fall Week 744 Scanner s=new Scanner(System.in); int [] a=new int [10]; for( i=0; i<10; i++){ a[i]=s.nextInt(); // Sets a[i] to number entered. } // End of for

Problem 3: Find average of numbers in an array 10/5/2011 final int n=100;// Array size double [] rnum=new double [n]; // Create array to hold numbers for( int i=0; i<n; i++){ rnum[i]=Math.random() // Initialize the ith element } // End of for double sum=0.0; // Initialize sum. for( int i=0; i<n; i++){ sum-sum+rnum[i]; // Add the ith element to sum } // End of for double average=sum/n; ©Aditya Mathur. CS 180. Fall Week 745

Problem 4: Count positive (including 0) and negatives. 10/5/2011©Aditya Mathur. CS 180. Fall Week 746 int sum=0; int [] a={-2, 12, 30, -4, 90}; int pos=0, neg=0; // Initialize counts. for(int i=0; i<a.length; i++){ if(a[i]>=0){ pos=pos+1; // Increment positive count }else{ neg=neg+1; // Increment negative count } }// End of for i++ is equivalent to i=i+1;

Problem 5: Search in an array: Step 1 initialize 10/5/2011 String [] wList={"Emilio", "Semion", ”Ziggy"}; Scanner s=new Scanner (System.in); String wanted=s.next(); // Get name to be searched boolean found=false; // Not yet found ©Aditya Mathur. CS 180. Fall Week 747

Problem 5: Search in an array: Step 2 set up loop 10/5/2011 boolean found=false; // Not yet found int next=0; // Points to the first element in wanted list while(???) { if(wanted.equals(wList[nextItem])) // Compare found=true; // If equal then we have found the wanted! else next=next+1; // else point to the next item on the list }//End of loop ©Aditya Mathur. CS 180. Fall Week 748

Problem 5: Search in an array: Step 3 complete loop condition 10/5/2011 int next=0; // Points to the first element in wanted list boolean found=false; // Not yet found while(next<wList.length&&!found) { if(wanted.equals(wList[next])){ // Compare found=true; // If equal then we have found the wanted! }else{ next=next+1; // else point to the next item on the list } }//End of loop ©Aditya Mathur. CS 180. Fall Week 749

Problem 5: Search in an array: Display output 10/5/2011 if(found) System.out.println(wanted+ " exists in database"); else System.out.println(wanted+ " not in database") } // End of program ©Aditya Mathur. CS 180. Fall Week 750

Problem 6: Sort an array in ascending order 10/5/2011 Example: Input array of integers: [ ] ©Aditya Mathur. CS 180. Fall Week 751 Sorted array of integers: [ ]

Problem 6: Sort algorithm: Bubble sort (Compare and exchange) 10/5/2011©Aditya Mathur. CS 180. Fall Week 752 Pass 1 Step End of pass 1 Pass 2 Step End of pass 2 Total 3 steps in Pass 1 Total 2 steps in Pass 2

Problem 6: Sort algorithm: Bubble sort 10/5/2011©Aditya Mathur. CS 180. Fall Week 753 Pass 3 Step Total 1 step in Pass 3 End of pass

Problem 6: Sort algorithm: Bubble sort: Analysis 10/5/2011©Aditya Mathur. CS 180. Fall Week 754 Given: Array of n elements Number of passes needed: Number of steps (comparisons) in Pass 1: Pass 2:. Pass i: Total number of steps:

Problem 6: Sort algorithm: Bubble sort: Warning 10/5/2011©Aditya Mathur. CS 180. Fall Week 755 Bubble sort is not a recommended algorithm for large arrays (e.g. an array of, say, 100 elements). Better algorithms: Insertion sort Merge sort Quick sort Challenge: Code the bubble sort algorithm (on your own).

Problem 7: Plant biology: Statement 10/5/2011 A plant biology lab maintains a collection of leaves. The lab director wishes to create a simple database that contains several entries. Each entry is a plant name, type of its leaf, and a brief description of the leaf in the collection. Example: WhitePine Needle NA Heather Compound NA Write a program that reads data from a file as mentioned above and allows a user to search for a tree in the database. ©Aditya Mathur. CS 180. Fall Week 756

Problem: Understanding 10/5/2011 A plant biology lab maintains a collection of leaves. From where can my program read the leaf data? If it is in a file, then what is the name of that file? The lab director wishes to create a simple database that contains several entries. How much data is available? Write a program that reads data from a file as mentioned above and allows a user to search for a tree in the database. In what form will the user input a request? ©Aditya Mathur. CS 180. Fall Week 757

10/5/2011 Java program for plant biology lab. Incremental stepwise development! ©Aditya Mathur. CS 180. Fall Week 758

Tasks 10/5/ Read plant collection data from a file 2.Provide search service to the user 3.Exit with a bye bye message when done. ©Aditya Mathur. CS 180. Fall Week 759

Let us assume…. 10/5/ LeafCollection class is available 2.It provides the following methods: createCollection() searchService() 3.Leaf class is available. It provides the following methods: public void getTree(); public void getLeafType(); public void getDescriptionType(); ©Aditya Mathur. CS 180. Fall Week 760 Why did we make the above assumptions?

Overall design: Classes 10/5/2011 LeafCollectionServer Main server Initiates actions ©Aditya Mathur. CS 180. Fall Week 761 Uses Leaf private String parentPlant; private String leafType; private String leafDescription; public String getTree(); public String getLeafType(); public String getDescriptionType(); Uses

LeafCollectionServer 10/5/2011©Aditya Mathur. CS 180. Fall Week 762 Back to the Java program. Version 1.0.

LeafCollection: Design 10/5/2011 Question: How should we store leaf collection data? Recall: For each leaf, we have its parent tree, its type, and its description. ©Aditya Mathur. CS 180. Fall Week 763 This is a class. Provides two methods: createCollection() searchService() But before we can write these methods we must have a way to read from a file and save in memory all the data about the collection!

LeafCollection: Design Question 10/5/2011 Question: How should we store leaf collection data? Recall: For each leaf, we have its parent tree, its type, and its description. ©Aditya Mathur. CS 180. Fall Week 764 Answer: ??

LeafCollection 10/5/2011©Aditya Mathur. CS 180. Fall Week 765 Back to the Java program. Version 2.0.

Leaf: Design: Attributes 10/5/2011©Aditya Mathur. CS 180. Fall Week 766 Recall, for each leaf, we have the following available data: Name of parent tree Name of the leaf Description

Leaf: Design: Methods 10/5/2011©Aditya Mathur. CS 180. Fall Week 767 Recall, for each leaf, we have the following available data: public String getLeafName(); public String getTreeName(); public String getDsecription();

Leaf class 10/5/2011©Aditya Mathur. CS 180. Fall Week 768 Back to the Java program. Version 3.0.

10/5/2011©Aditya Mathur. CS 180. Fall Week 769 Arrays: Multidimensional

Example 1 10/5/2011©Aditya Mathur. CS 180. Fall Week 770 FLAGSTAFF PHOENIX TUCSON WINSLOW YUMA MEAN MONTHLY CLOUDY DAYS IN ARIZONA J F M A M J J A S O N D int [][] cloudyDays=new int [5][12 ] rowscolumns What is the value of cloudyDays[1,8]?

Declaration 10/5/2011 Cars [] inventory=new Car [3][]; 3 rows and undefined number of columns Each row represents make of a car and column represents models ©Aditya Mathur. CS 180. Fall Week 771 Chevy0 Honda1 Toyota2 AvalancheTraverse AccordFitCivic CamryCorollaRav4 021

Arrays: Typical errors 10/5/2011 Index out of bounds [Run time error] int [] a=new int [10]; a[i]=x; // i is greater than 9 or less than 0 Element not initialized [Compile time error] String [] name; name[i]=“Bob”; // element not initialized ©Aditya Mathur. CS 180. Fall Week 772

Week 7: October 3-7, 2011 Hope you enjoyed this week! Questions? Contact your recitation instructor. Make full use of our office hours. 10/5/2011©Aditya Mathur. CS 180. Fall Week 773