Documente Academic
Documente Profesional
Documente Cultură
4th
Instructor:
12/29/06
Instructor:
12/29/06
Special Thanks to Lee Garza for having faith in my teaching ability back in 1996 and to Pat Baker for giving me much advice on teaching and technology.
January 1, 2007
12/29/06
Contents
Syllabus Complete Presentation Project Requirements Document Supplemental Reading
12/29/06
12/29/06
Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session
Narrative
This document is the project description roadmap for the CSC205 course. It contains project descriptions for all software projects in the CSC205 course. Homework Problems There are 15 Java programs to be written throughout the semester. These programs are a combination of computer science based problems designed to reinforce the course material. Each problem should be turned in separately, stapled together with a cover page. All programs, labs and homework, should have your name, class, problem number and date in comment form in the programs header similar to below.
// // // // // // // // ---------------------------------------------------------Program Name: Prob11.java Problem Number: Project-11 Author: Your Name Course: CSC205 Date: August 19, 2004 Description: This program does the following: some text ----------------------------------------------------------
This may look daunting but is very easy once you analyze the problem and break it down into loops and terms. Take each term and find the similarities and sequences. For instance, the exponents are 2, 4, 6, 8, 10, etc for the cosine and 3, 5, 7, 9, etc for the sine. This can easily be controlled in a for loop. You will need a factorial function for the denominator but notice the sequence here, too. The factorial is the same number as the exponent in the numerator. Notice the alternating signs between the terms. Each term should be represented by an iteration of a loop. When you iterate about 20 times, or so, you get an approximation to the sine and cosine.
HW-1
Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session
So, once you have the sine and cosine methods tested and debugged, then they can be used to derive the tangent.
: : : : : : : : : : : :
return return return return return return return return return return return return
int int Boolean Boolean int count of the search value int count of the search value double mean value of integers long a reference to the array void void the time in milliseconds
HW-2
Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session
: Sets the starting time value : Sets the stop time value
Technically, methods c and d, above could be accomplished in a single method. Its your choice. Example, Note that the exists() methods and the setValue() methods are overloaded methods.
3.)
HW-3
Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session
Stack Project
1) Emulate a stack by using the Java Linked List class. Push and pop 10,000 random numbers onto the stack. Do a timing analysis. How many can you push onto the stack before you throw a memory exception? Catch the exception. Create a stack class using Javas built-in Stack Class. Push and pop 10,000 random numbers. Do timing analysis. How many can you push onto the stack before you throw a memory exception? Catch the exception. Create a stack class that pushes a random number of objects onto a stack and pops a random number of objects off the stack. Keep track of the exceptions when the stack is empty and when the stack overflows.
2)
3)
Queue Project
Part-1: Here is the algorithm in pseudocode for part-one. Use a Linked List class to emulate the queue. Loop 10,000 times { Generate a random number, n, between 0 and 100. Add n 4-byte string objects to the head of the linked-list. Generate a random number, m, between 0 and 100. Remove m objects from the tail of the lined-list. } Catch all exceptions What is the final size of the linked list? Part-2 Now, go to the web and look up the specification for PriorityBlockingQueue. Repeat Part-1 only this time using the Java-provided PriorityBlockingQueue methods. Which is faster, the linked list or the Java PriorityBlockingQueue class?
Recursion Project
Create a Java class that computes the factorial of a number that is input from the keyboard from a Swing Dialog input box like the one displayed on the right. A factorial is the product of all the numbers up to the number entered. For example, 6-factorial is 720 because 6*5*4*3*2*1 is 720. Six-factorial is written 6! Prompt the user for the numeric input. Keep prompting for values until a zero value is entered. Document your code with plenty of comments. Use recursion. Do the same using the Fibonacci algorithm. You can find this algorithm on the web.
HW-4
Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session
Searching Project
Linear and Binary Search Comparison. Randomly populate an array with 10,000 integers. Use the Array Utility Class designed earlier to populate the array. Sort the array in ascending order using the sort algorithm of your choice. Prompt the user for a number to find using a Swing Dialog Box like the one to the right. Search the array using the binary search algorithm and the linear search algorithm. Show the number of iterations or compares it took to find the data using each search algorithm. Also, show a message should there be a no find condition for the number being sought.
Sorting Project
Create three different Java classes to sort data and analyze the five different sort algorithms. 1) Exchange 2) Selection 3) Insertion Write a Bubble Sort (Exchange Sort) class. Randomly populate an array with 10,000 integers. Use the Array Utility Class designed above to populate the array. Sort the array in descending order. Show the number of iterations and swaps and the time in milliseconds it took to sort. This second class will call a Selection Sort class. Randomly populate an array with 10,000 integers. The Array Utility Class designed above to populate the array. Sort the array in descending order. Show the number of iterations and swaps and the time in milliseconds it took to sort this data. Do the same for the Insertion Sort. Add a summary page describing the complete analysis of these sorting algorithms. The goal of this project is to determine which sort method is the quickest.
HW-5
Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session
string and search the hash set for the entered value. Print appropriate error messages if a no- find condition exists.
Vectors Project
Write a Java class that uses the Vector class. Load your vector object with 2,500 random numbers that you convert to individual objects using the Integer wrapper class. Then, loop through and print the first 50 number. Loop, again, and write all 2,500 Integer objects to a disk file using Java File I/O.
HW-6
Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session
Swing Project
Using the Java Swing component set, develop your very own file dumper class. This class simply uses the JFileChooser to select a file of your choice. It then opens the file and displays every byte of information in a JTextArea component. Each byte is displayed in hexadecimal. This class should process the input file as binary file so as to obtain each carriage return and line feed to be displayed in your output area. Be sure to include a JMenu for the File Open, Close and Exit functions. Your text-area should look something like this:
HW-7
Course Roadmap and Homework Assignments for Data Structures and Algorithms (Java)
Updated on 01/11/2007 for the Spring 2007 Session
Statistics Project
This final project deals with arrays and algorithms to calculate some statistics of a data sample. These algorithms show up often in both business and engineering therefore they are very relevant to our learning. The math looks scary but when broken down into components of loops and arrays, the process is easy. Take the mean value of a set of numbers N. The expression below describes the mean in a formal way. Said differently, we sum all the values in the set N and divide by the count. For instance, if we had 75 numbers we sum all 75 numbers and divide by 75 to get the mean, or average, value.
The Project Your project is to provide two separate input paths for the sample data. The first is a manual prompt using a JOptionPane and the other is from a disk file. Each value you harvest is stored in an array element. The Algorithm for Standard Deviation 1. Get the count n of the elements in the array 2. Find the average of all the array elements (xi) 3. Make a second array with the mean minus each original element (xi-x) 4. Square each element of the new array (xi-x)2 5. Get the sum of all the squared elements 6. Divide the sum by n-1 to get the variance 7. take the square root of the variance to get the standard deviation Your Java project should read in a bunch of numbers and subsequently calculate the mean, mode, median and standard deviation. The mode is the most common value. The median is the middle point of the sorted array values.
HW-8
Subject Overview
Advanced Data Structures (CSC205)
An Excellent Text
SLIDE-3
SLIDE-4
SLIDE-5
Class Structure
Discussions During Each Class
Java, Software Engineering, Computer Science, Abstract Structures
Deliverables
Two Tests Two Exams 15 Java Classes as Homework Projects 11 In-Class Lab Assignments One Critical Thinking Paper
SLIDE-6
Homework
See separate Homework Roadmap Document in the tail section of this manual
Class-1 January 22 - Introduction Week In Class: Plan on covering the course syllabus, grading policy, homework projects and some basic software engineering techniques. We will discuss where data structures are used and some Java terminology. We will begin chapter one in the textbook on the object oriented concepts and the phases of software development. Reading: Read Chapter 1 in the text book by Frank Carrano and Janet Prichard. Deliverables: Review and familiarize yourself with this roadmap document. Start researching information for your semester paper, titled, Everything You Ever Wanted to Know About Java Generic Programming Homework: Email Synchronization. Send me an email explaining what you want to learn in this course. Also, state what you feel will be your biggest challenge in this course. Send the email to jimadams@softwaredynamix.com Tests: None.
SLIDE-7
Grading
Grading 100% - 90% A 89% - 80% B 79% - 70% C 69% - 60% D Below 60 Oops
Grading Policy
Assignments are presented with the intent of reinforcing the reading material and topics discussed in the classroom. Late assignments are welcome, but receive a 10 percent reduction for each week they are late. All external class assignments are expected to be typed.
SLIDE-9
Grade Distribution
Activity Percent Midterm Exam 20 % Final Exam 24 % 2 Tests 10 % Homework Projects (15 Total) 30 % In Class Labs (11 Total) 11 % Critical Thinking Paper 5% Total Extra Credit Papers 100 % 5%
SLIDE-10
SLIDE-11
SLIDE-12
Plagiarism
Statement Concerning Plagiarism Plagiarism is defined as presenting the work of another as one's own. More than four consecutive words from a source other than the writer constitute plagiarism when the source is not clearly identified in appropriate documentation format. From the CGCC Student Handbook: "Plagiarism includes, but is not limited to, the use of paraphrase or direct quotation, of the published or unpublished work of another person without full and clear acknowledgement. It also includes the unacknowledged use of materials prepared by another person or agency engaged in the selling of term papers or other academic materials."
SLIDE-13
SLIDE-14
SLIDE-15
Division Secretary: Carlene Weberg (480) 732-7043 Software and Systems Engineer since 1978 Teaching at CGCC since 1996 (WIU in 1997, GCC in 1998) Programmed FORTRAN, COBOL, C#, C++, Assembler, VB, Java, Perl, PHP Today all Java and C# BS in Engineering, Mathematics Major MBA Technology Management MS Systems Engineering
SLIDE-16
Summary
Text Book Homework & Labs Attendance Class Structure Grading Instructor Contact Information Upon completion of this course, you will have a crisp outlook and deep understanding of some of the critical data structures used in software engineering. Sound Exciting?
Lets go.
SLIDE-17
1. 2. 3. 4. 5. 6. 7. 8. 9.
Program Correctness JavaDoc and Java Comments Meaningful Variable Names Constants Code Blocks and White Space Cohesion and Coupling Accessor and Mutator Methods Side Effects Static Methods and Static Fields
Pass in Arguments
Method
Return a Result
SLIDE-19
A correct program does what it is supposed to do. It conforms to its subdivided specifications, in that its output is correct for ANY acceptable input. Clarity A clear program is easy for people to understand. This is important because 90% of the cost of a large program is writing and maintenance Organize your program into segments
Provide each segment with a heading Subdivide your program
SLIDE-20
double char
J23qrsnf abcd;
int int
Adder; adder;
Java Constants
Constants are noted as final values in Java
final final final final final double NICKEL_VALUE double PI char LF char CR double E = = = = = 0.05; 3.14159265; 10; 13; 2.71828
SLIDE-22
Magic Numbers
Dont use magic numbers Magic numbers are constants that appear in your code
h = 31 * h + ch;
What is the 31? Number of days in December? One less than the ASCII space value of 32? One less than the number of bits in an integer?
final int DAYS_IN_DECEMBER = 31; Much more clear h = DAYS_IN_DECEMBER * h + ch;
int SPACE = 32; int LINEFEED = 10; double SQUARE_ROOT_OF_TWO = 1.414213 double PI = 3.1459
Copyright 2004-2007, Jim Adams SLIDE-23
SLIDE-24
SLIDE-25
Designing Classes
Classes are named after objects, like nouns
Vehicle class Bank Account class Furniture class Phone class Person class car, truck, etc savings, checking, IRA, mortgage, etc chair, bed, table, lamp, etc cell, analog, digital, home, work man, woman, kid, boy, girl, etc
SLIDE-26
Designing Classes
Classes have methods that represent action, like verbs Vehicle class
start_vehicle() stop_vehicle() get_mileage() get_mpg() set_parking_brake() reset_odometer(); get_odometer_reading();
BankAccount class
Deposit(account, amount, date); Withdrawal(account, amount, date); Inquiry(account); Open(account, first name, last name, date); Close(account, date);
Phone class
Initiate_call(number); Answer_call();
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-27
SLIDE-29
12 combinations in all Or, do we make a generic method and pass the input and out base.
SLIDE-31
SLIDE-32
Class Cohesion
Cohesive means a public interface is closely related to the single concept that the class represents For example, this class lacks cohesion:
public class { public public public public public public public public } Purse Purse(){...} void addNickels(int count){...} void addDimes(int count){...} void addQuarters(int count){...} double getTotal(){...} static final double NICKEL_VALUE =0.05; static final double DIME_VALUE =0.1; static final double QUARTER_VALUE =0.25; ...
Class Cohesion
Solution: Make two classes:
public class Coin { public Coin(double aValue,String aName){...} public double getValue(){...} } public class Purse { public Purse(){...} public void add(Coin aCoin){...} public double getTotal(){...} }
SLIDE-35
Coupling
A class depends on another if it calls one of its methods High Coupling = many class dependencies Minimize coupling to minimize the impact of interface changes
SLIDE-36
Dependency Relationships
Purse Class depends on the Coin Class. Coin does NOT depend on Purse
SLIDE-37
SLIDE-38
Dependency Relationships
This concept can become tricky and confusing. Do we link (instantiate) another class to get an object or recode the methods in our base class? Do we inherit or do we make an interface? Example: Application that uses XML file access Do we make a separate XML class that reads and writes and otherwise processes XML files, or Do we include the XML routines in the base class. Effect If we inherit the standalone XML class then we need to include that class whenever we distribute the base class. If we include, or incorporate, the XML class methods into the base application, then we can distribute one class.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-39
SLIDE-40
SLIDE-41
Side Effects
Side Effect: any observable change outside the implicit parameter like doing something other than what the method was designed to do. Example: Getter method that updates
public double balanceInquiry(BankAccount acct) { this.inquiry_date = Date(today); // questionable sendUserEmail(client_name, acct); // definite side effect this.inquiries++; // definite side effect return(this.balance); // okay }
SLIDE-42
Side Effects
public void deposit(double amount, BankAccount acct) { this.balance = this.balance + amount; } // No Side Effect
public void deposit(double amount, BankAccount acct) { this.balance = this.balance - amount; printBalance(acct); // Side Effect } // In the main, call the methods separately deposit(1234.90, "YourAccount"); printBalance("YourAccount");
SLIDE-43
Static Methods
Every method must be in a class All methods wrote up to now are Instance Methods Static Methods are sometimes called Class Methods Math.sqrt(x) Math is a Class and acts like an object
Public static boolean approxEqual(double x, double y) { final double EPSILON = 1E-14; if (x==0) return Math.abs(y); if (y==0) return Math.abs(x); return Math.abs(x-y); } Notice no local variables. We do not need a copy of this function each time we call it. Static methods can only be invoked by a class name, not an object name
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-44
Static Fields
One field per class
public class BankAccount Static { private double balance; private int accountNumber; Stack private static int lastAssignedNumber; } Heap public BankAccount() { lastAssignedNumber++; // increment static field accountNumber = lastAssignedNumber; // set instance field }
SLIDE-45
SLIDE-46
Scope
Scope of variable: region of program where you can refer to the variable by its name Local variable scope: from definition to end of block Class scope: all methods of the class Must qualify public members outside scope, e.g. Math.sqrt
public class BankAccount { private double balance; // class scope private int accountNumber; private static int lastAssignedNumber; public BankAccount() { long newAccountNumber=0; // local scope lastAssignedNumber++; accountNumber = lastAssignedNumber;
} } // end of class
SLIDE-47
Scope
Overlapping scope: local scope wins over class scope
public class Coin { public void draw(Graphics2D g2) { String name = "SansSerif"; // local scope g2.setFont(new Font(name, . . .)); // local name g2.drawString(this.name, . . .); // field name } private String name; . . . } // class scope
SLIDE-48
SLIDE-49
Scope
Instantiating an Object from a Class
public static void main(String[] args) { Encrypter enc = new Encrypter(90); enc.somePublicMethod(); } public class Encrypter { private int counter=0;
// class variable
SLIDE-50
Coupling Example
public class Driver { public Driver() { }
Using Our Project as an example
public static void main(String[] args) { Harvest h = new Harvest(); // Get a Public Variable System.out.println(h.count); System.out.println(Harvest.cnt); // Get a static Variable System.out.println(h.getCounter()); // Get a private Var } }
SLIDE-51
Coupling Example
public class Harvest { private int counter=80; public int count=90; public static int cnt=100; public Harvest() { } public int getCounter() { return(counter); } }
// private instance Variable // public instance Variable // public static Variable
SLIDE-52
Summary
Program Correctness Javadoc Class Design Java Constants Variable Scope Static Methods Coupling Accessor and Mutator methods Further Research Javadoc Designing Classes Static Variables and Methods Use Cases UML Diagrams Extreme Programming SDLC Waterfall Methodology Spiral Model Concurrent Development Model Agile Development Navigation Analysis Systems Theory
Software Engineering, Sixth Edition by Roger Pressman Software Engineering Volume 1: The Development Process. IEEE Press.
SLIDE-53
Java Inheritance
Goals To understand inheritance To understand software reusability
Inheritance
Often you will be in a situation where a class is close to what you need. Perhaps the class you need requires some minor alteration
Adding a few methods Changing a few methods
Java, and Object Oriented Languages in general, provide support for this type of situation. The original class is called the Super Class (or
Parent Class or Base Class)
SLIDE-55
Extending a Class
Extending a class
Defining a new class (to create a new type) can involve a lot of effort. Sometimes you have an option that can greatly reduce the effort required to create your new type. If a class (type) already exists that is close to what you need, you can often extend that class to produce a new class that is closer to what you need. In many cases, this will require much less effort than that required to start from scratch and define a new class to establish a new type. The ability to extend one class into another new class is the essence of inheritance. According to the current jargon, the new class is called the subclass and the class that was extended is called the superclass.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-56
Extending a Class
What is inherited?
The subclass inherits all of the variables and all of the methods defined in the superclass It's like you had completely defined the new class from scratch and reproduced all of the code already defined in the existing superclass.
Code reuse
Inheritance makes it possible to define a new class with a minimum requirement to write new code by reusing the code that was previously written into the superclass. Sometimes you can get by with simply extending the existing class. Sometimes it is necessary to make changes to the existing class to improve its ability to be extended in a meaningful way. It all depends on how the existing class was designed in the first place.
SLIDE-57
Inheritance
Let's Look At A Bank Account We can have many types of accounts.
Savings Personal Checking Business Checking Student Loans Home Loans Certificate of Deposit
SLIDE-58
Inheritance
Let's Look At A Vehicle We can have many types of vehicles.
Cars Trucks Pick-up Trucks SUV's Golf Carts
SLIDE-59
Inheritance
Bank Account Class Vehicle Class
Savings Account and Checking Account Class Would Extend the Bank Account Class
SLIDE-60
public void setEngineSize(int ci) { System.out.println("Setting Engine Size to " + ci + " Cubic Inches"); } public void setTransmissionSpeeds(int gears) { System.out.println("Setting Transmission to " + gears + "-Speed"); } public void startEngine(String msg) { System.out.println("Starting the " + msg); } public void moveForward(String msg) { System.out.println("Moving the " + msg + " forward"); } public void turnLeft(String msg) { System.out.println("Turning the " + msg + " to the left"); }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-61
SLIDE-62
public class Truck extends Vehicle { public Truck() { setEngineSize(427); // derived from Vehicle Class setTransmissionSpeeds(4); startEngine("Truck"); moveForward("Truck"); turnLeft("Truck"); lowerTailGate(); } private void lowerTailGate() // specific to truck class { System.out.println("Lowering Tail Gate"); } }
SLIDE-63
Inheritance
Let's look at some more techniques used by Java super this
SLIDE-64
}
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-66
public class Car extends Vehicle { String carModel; public Car(String model) { super.vehicleModel = model; // sets model in super class this.carModel = model; // sets model in this class setEngineSize(283); setTransmissionSpeeds(3); startEngine("Car"); moveForward("Car"); turnLeft("Car"); getVehicleModel(); } }
SLIDE-67
Examples
Can you think of any examples of inheritance?
Construction Worker Two-Story Home Tiger Elephant Cuckoo Clock Dime Car JPanel
SLIDE-68
Examples
Can you think of any examples of inheritance?
Construction Worker Employee Person Two-Story Home Dwelling Tiger Carnivore Animal Organism Elephant Herbivore Animal Organism Cuckoo Clock Clock Dime Coin Money Car Vehicle JPanel JComponent
SLIDE-69
Examples
Swing Components
JComponent
JPanel
JTextComponent
JLabel
JAbstractButton
JTextArea
JTextField
JToggleButton
JButton
JCheckBox
JRadioButton
SLIDE-70
SLIDE-71
An Interface
Objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off. In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
SLIDE-72
An Interface
Creating your own interface. Notice the empty methods interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); }
SLIDE-73
An Interface
Is a model or template of an object. It has predefined methods in name only. You must supply the code. /* * Action Listener Interface */ private class PopUpMenuListener implements ActionListener { public void actionPerformed(ActionEvent e) { JMenuItem item = (JMenuItem) e.getSource(); String name = item.getName(); if (name.equals("Item13")) { addBreak(); } } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-74
// Break
An Interface
Is a model or template of an object
/** * Mouse Motion Listener. * Changes the mouse cursor * Sets global variables */ private class MouseHoverRight implements MouseMotionListener { public void mouseMoved(MouseEvent evt) { rightArrow.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); rightArrow.setToolTipText("Move Forward One Day"); } public void mouseDragged(MouseEvent evt) { } }
SLIDE-75
Code reuse pays off for ING - The company saved about $300,000 and 1,200 manhours ComputerWorld. News Story by Lucas Mearian. JANUARY 10, 2005. Code reuse: Does anyone still do this? (Jeff Key Web Site) It startles me whenever I see add-ins, IDEs or people touting code libraries and code reuse. Is anyone still copying and pasting code? I have a couple standard comment headers and whatnot that I store in the VS.NET toolbar for reuse, but no code. With all of the template-based code generators available now, I can't imagine why anyone would do this. On a related note, I get the heebie-jeebies when people mention pulling code from old apps to reuse in a new app, even if it was their own code. The great thing about being in this profession is that you learn every day. Any time anyone mentions pulling old code, I suggest pulling the ideas and leave the code where it is. The hard part isn't writing the code, it's the concept behind it. Take what you've learned and write something new and wonderful. Conceptual reuse, that's where it's at.
Copyright 2004-2007, Jim Adams SLIDE-76
SLIDE-77
Design Patterns
Design Patterns
Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.
SLIDE-78
Summary
Summary Extending an existing class often provides an easy way to create a new type. This is primarily true when an existing class creates a type whose features are close to, but not identical to the features needed in the new type. When an existing class is extended to define a new class, the existing class is often called the superclass and the new class is often called the subclass. The subclass inherits all of the variables and all of the methods defined in the superclass and its superclasses. Inheritance provides a formal mechanism for code reuse.
SLIDE-79
Software Engineering
1. 2. 3. 4. 5. 6. 7.
Software Engineering Processes Software Development Phases Specification and Design Methodologies Software Analysis Software Failure Issues Faced Today UML, Preconditions, Post Conditions
What is Engineering?
The use of scientific (including mathematical) principles to construct artifacts "Application of knowledge of the mathematical and natural sciences, gained by study, experience and practice, to the efficient use of the materials and forces of nature". (MS Encarta) "Creation and design of practical solutions to real physical problems"
SLIDE-81
The construction of quality software with a limited budget and a given deadline in the context of constant change. The establishment and use of sound engineering principles in order to obtain, economically, software that is reliable and works efficiently on real machines.
(Bauer 1969)
SLIDE-82
SLIDE-83
Software Failures
Patriot missile 1991 The Patriot system at Dhahran failed to track and intercept the Scud missile because of a software problem in the system's weapons control computer. This problem led to an inaccurate tracking calculation that became worse the longer the system operated. At the time of the incident, the system had been operating continuously for over 100 hours. By then, the inaccuracy was serious enough to cause the system to look in the wrong place for the incoming Scud missile Ariane 5 rocket 1996 On June 4, 1996 an unmanned Ariane 5 rocket launched by the European Space Agency exploded just forty seconds after its lift-off from Kourou, French Guiana. The rocket was on its first voyage, after a decade of development costing $7 billion. The destroyed rocket and its cargo were valued at $500 million. The cause of the failure was a software error in the inertial reference system. Specifically a 64 bit floating point number relating to the horizontal velocity of the rocket with respect to the platform was converted to a 16 bit signed integer. The number was larger than 32,767, the largest integer store-able in a 16 bit signed integer Taurus (London stock exchange system) 1993 Another failure was the collapse of the Taurus trading system of the London Stock Exchange. Taurus would have replaced the shuffling of six sorts of paper among three places over two weeks with a computerized system able to settle trades in three days. The five-year Taurus development effort, which sources estimated cost hundreds of millions of dollars, was termed a disaster, and the project was abandoned in March 1993.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-84
Software Failures
Denver airport baggage handling system Despite the fact that a company well known for being "among the best" who worked on the DIA Baggage Handling System, BAE Automated Systems, there were so many problems that it caused the DIA opening to be postponed 4 times. Mostly managerial and social factors caused most of the major problems with this baggage system. They made it much more complex, having BAE to design the baggage system around the architecture of the airport. There was an obvious lack of communication and proper planning with the designers and the managers. London ambulance system (1993) In Britain, 1993, an incident occurred which forced the London Ambulance Service to abandon its emergency system after it performed disastrously on delivery, causing delays in answering calls. An independent inquiry ordered by British government agencies found that the ambulance service had accepted a suspiciously low bid from a small and inexperienced supplier. The inquiry report, released in February 1993, determined that the system was far too small to cope with the data load. For an emergency service, the system error would not only cause the loss of money, but more essentially, fail to dispatch ambulances correctly and promptly upon the arising of critical situations. Therac-25 Radiation Machine Between June 1985 and January 1987, six known accidents involved massive overdoses by the Therac-25 -- with resultant deaths and serious injuries. They have been described as the worst series of radiation accidents in the 35-year history of medical accelerators.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-85
SLIDE-87
SLIDE-88
SLIDE-89
Ease of Use
Prompt the user for input values Echo the input
SLIDE-90
Style
Extensive use of methods Use private data fields Error handling Readability Documentation
SLIDE-91
SLIDE-92
Define objectives Preliminary design of classes Write the code Compile the code Run the program Test and debug Maintain and modify Document
SLIDE-94
SLIDE-95
Waterfall Methodology (1 of 2)
Analysis Decide what the project is suppose to do Output: requirements document Design Plan how to implement the system Output:
description of classes and methods diagrams showing the relationships among the classes
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-96
Waterfall Methodology (2 of 2)
Implementation Write and compile the code Output: completed code Testing Run tests to verify the program works correctly Output: a report of the tests and their results Deployment Install the program and begin using it
SLIDE-97
Systems Analysis
Implementation
SLIDE-99
Start Here
SLIDE-100
SLIDE-101
SLIDE-103
Many Methodologies
1. Basic Design Methodology 2. Analysis and Design Methodology 3. Waterfall Methodology 4. Spiral Methodology 5. SDLC 6. Extreme Programming Methodology (XP) 7. Agile Development Methodology 8. PBR Plan, Build, Run 9. SCRUM 10. Adaptive Software Methodology 11. Crystal
Software Engineering. Theory and Practice. (2006). Pfleeger and Atlee.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-104
SLIDE-105
SLIDE-106
State Diagram displays the sequences of states that an object of an interaction goes through during its life in response to received stimuli, together with its responses and actions Activity Diagram displays a special state diagram where most of the states are action states and most of the transitions are triggered by completion of the actions in the source states. This diagram focuses on flows driven by internal processing Physical Diagrams
Component Diagram displays the high level packaged structure of the code itself. Dependencies among components are shown, including source code components, binary code components, and executable components. Some components exist at compile time, at link time, at run times well as at more than one time Deployment Diagram displays the configuration of run-time processing elements and the software components, processes, and objects that live on them. Software component instances represent run-time manifestations of code units.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-107
SLIDE-108
SLIDE-109
SLIDE-110
SLIDE-111
SLIDE-112
SLIDE-113
SLIDE-114
SLIDE-115
SLIDE-116
SLIDE-117
SLIDE-118
Example
You are the head of a programming team and you want one of your software developers to write a method for part of a project.
HERE ARE THE REQUIREMENTS FOR A METHOD THAT I WANT YOU TO WRITE.
I DON'T CARE WHAT ALGORITHM THE METHOD USES, AS LONG AS THESE REQUIREMENTS ARE MET.
SLIDE-120
One way to specify such requirements is with a pair of statements about the function. The pre-condition statement indicates what must be true before the function is called. The post-condition statement indicates what will be true when the function finishes its work.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-121
Example
void { // // // } writeSqrt( double x) Precondition: x >= 0. Postcondition: The square root of x has been written to the standard output.
SLIDE-122
Example
Which of these method calls meet the precondition ?
writeSqrt(-10); writeSqrt(0); writeSqrt(5.6);
void { // // // }
writeSqrt( double x) Precondition: x >= 0. Postcondition: The square root of x has been written to the standard output.
SLIDE-123
Example
void { // // // } writeSqrt( double x) Precondition: x >= 0. Postcondition: The square root of x has been written to the standard output.
The post condition always indicates what work the function has accomplished. In this case, when the function returns the square root of x.
SLIDE-124
Another Example
bool { // // // // // // } is_vowel( char letter ) Precondition: letter is an uppercase or lowercase letter (in the range 'A' ... 'Z' or 'a' ... 'z') . Postcondition: The value returned by the function is true if Letter is a vowel; otherwise the value returned by the function is false.
true
What values will be returned by these method calls ? is_vowel( 'A' ); is_vowel(' Z' ); is_vowel( '?' );
Careful programmers follow these rules: When you write a method or function, you should make every effort to detect when a precondition has been violated. If you detect that a precondition has been violated, then print or display an error message and halt the program.
SLIDE-126
Summary
Summary
1. 2. 3. 4. 5. 6.
Engineering Methodologies Software Engineering Processes Software Development Phases Specification and Design Methodologies Implementation of Software Applications Software Failure Code of Ethics
SLIDE-127
Algorithms
1. 2. 3. 4. 5.
Software Algorithms Time Analysis Software Testing Big O Notation Debugging Techniques
SLIDE-129
Algorithms
Series Expansion Algorithms
Taylor Series
1. 2. 3. 4.
Analyze the algorithm Look for similarities in each term Numerator has x1, x3, x5, x7, xn The denominator is the same as the numerator exponent as a factorial Each term can be solved inside a loop Could make a method for the denominator and one for the numerator
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-130
5. 6.
Algorithms
Series Expansion Algorithms
Where would you start on the cosine expansion above? Taylor Series Expansion for Cosine
SLIDE-131
Algorithms
Series Expansion Algorithms Output 20.085536921517665 Where would you start on the expansion above?
public double e(double x) { double result double numerator double denominator for (int n=0; n<20; { numerator = denominator = result = } return(result); } n++) Math.pow(x,n); factorial(n); result + (numerator / denominator); =0.0; =0.0; =0.0;
SLIDE-132
Algorithms
Hundreds of Series Expansion Algorithms Binomial Statistical Exponential Trigonometric Differentials Integrals Fourier Transformations Encryption
SLIDE-133
SLIDE-134
Time Analysis
Methods 1. Count the number of loop iterations, swaps, etc 2. Count the times each array element is accessed 3. Devise a software stopwatch and count the milliseconds of time during execution 4. Sum up all the actions Each access takes some amount of CPU cycles Some more, some less, but they all take cycles Assume an if test takes 20 cycles per use, for example Assume an assignment statement takes 8 CPU cycles 5. Count the number of Operators Uses Big O Notation
SLIDE-135
Time Analysis
Time for f(n) instructions to execute on a machine that executes 1 billion instructions per second. (1 Gigahertz)
SLIDE-136
Time Analysis
Consider the following example:
1. System.out.println(Enter a number); 2. count=0; 3. sum=0; 4. num=Integer.parseInt(keyboard.readLine()); 5. while (num != -1) 6. { 7. sum = sum + num; 8. count++; 9. num = Integer.parseInt(keyboard.readLine()); 10. } 11. if (count != 0) 12. average = sum/count; 13. else 14. average=0;
SLIDE-137
Time Analysis
The program has 4 operations before the while loop (Lines 2-5) It has 3 or 4 operations after the while loop, depending on the value of count (Lines 11-14) The while loop has one operator on line 5 with 4 operations inside the loop (Lines 7-9) So, if the loop executes 10 times then there are 51 operations (5 operations times 10 plus the while statement itself) plus 4 before the loop and plus 4 or 5 depending on count after the loop. Generalizing, it is (5n + 9) or (5n + 10) With very large values of n, say 10,000, the 9 and 10 terms become insignificant.
SLIDE-138
Time Analysis
Worst Case, Best Case and Most Likely Case t = (wc + 4*ml + bc) / 6 Example: Worst case Best case Most Likely = 40 ms = 10 ms = 16ms
Expected time = [40 + (4*16) + 10]/6 Expected time = [40 + 64 + 10]/6 Expected time = [114]/6 Expected time = 19 ms
SLIDE-139
Big O Notation discussion was an excerpt from Data Structures Using Java by D.S. Malik and P. S. Nair, pages 11-15 (2003) Also found on Wikipedia
SLIDE-140
n2
n log n
50 40 30 20 10 0 n
n log n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
SLIDE-141
SLIDE-142
Software Testing
Software Testability
Operability
The better it works, the more efficiently it can be tested
Observability
Bad output is easily found. Source code is accessible
Controllability
Ideally, tests can be specified, automated and reproduced
Decomposability
The software should be built from independent modules so testing can be done independently
Simplicity
The less there is to test, the quicker we can test it
Stability
Software recovers quickly and easily after a failure
Understandability
Source code is well commented, documented, and organized
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-143
Unit Test
Test your classes in isolation, outside the program in which they are used Test one class at a time Supply test inputs through a Test Harness A Test Harness is a program that feeds test inputs to a class
Class To Be Tested
SLIDE-144
From an application I wrote last year I created a series of tests that could be run selectively or all in a sequence
private static void indexedTest2() { AdvancedIO T1 = new AdvancedIO("C:TestFile_02","Indexed"); int status = T1.open("A"); if (status == SUCCESSFUL_IO) { System.out.println(T1.getIOStatus()); T1.append(record6[0], record6); T1.append(record6[0], record6); // duplicate key test. T1.append(record7[0], record7); T1.append(record8[0], record8); T1.append(record9[0], record9); T1.close(); } else { System.out.println("Index File Open Status:" + status); } }
SLIDE-145
Create a test harness that invokes your classes with known sets of data and compare the results Use a calculator and compare results manually Say you wrote a class to compute approximate square roots
You can feed some known values, say 4 and 100, knowing the answer will be 2 and 10
SLIDE-146
Test Cases
Positive test case: expect positive outcome Example: square root of 100 Negative test case: expect the program to reject these cases. Example: square root of -1 or square root of the letter Q Boundary test case: at boundary of domain Frequent cause for errors i.e. square root of 0
SLIDE-147
Manual Run the program over and over entering data manually Check property of result Example: the square root squared = original value Oracle = slower way of computing answer Example. square root of x = x1/2
SLIDE-148
Regression Testing
Save test cases to automate future testing java Program < test1.in > test1.out java Program < test2.in > test2.out java Program < test3.in > test3.out Repeat test whenever your program changes Test suite = collection of test cases Cycling = bug that is fixed but reappears in later versions Regression testing = testing against past failures
SLIDE-149
Test Coverage
Black-box testing: test functionality without understanding internal structure White-box testing: take internal structure into account when designing tests Performance testing Test coverage: the code that is actually executed during test cases Red Team Test: Hacking teams that try to break the code also called penetration testing. Red team groups develop mock attacks against critical infrastructures and other assets in order to understand events, improve systems, prioritize mitigation, and provide actionable information for decision makers. Regression Testing: Complete test from start to finish of the entire application Easy to overlook error branches during testing Make sure to execute each branch in at least one test case
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-150
Program Trace
Output statements in your program for diagnostic purposes
if (status == SINGLE) { System.out.println("status is SINGLE"); ... } Or if (DEBUGGING) // DEBUGGING is a boolean variable { System.out.println(some_variable); }
SLIDE-151
Program Trace
Stack trace tells you the contents of the call stack
Throwable t = new Throwable(); t.printStackTrace(System.out);
Drawback of trace messages: Need to remove them when testing is complete, stick them back in when another error is found
SLIDE-152
Logging
Get global logger object from java.util.*:
Logger logger = Logger.getLogger("global");
Log a message
logger.info("status is SINGLE");
SLIDE-153
The Debugger
Debugger = program to run your program, interrupt it, and inspect variables Three key commands:
Set Breakpoint Single Step Inspect Variable
SLIDE-155
Inspecting Variables
SLIDE-156
Debugging Techniques
Reproduce the error Simplify the error Divide and conquer Know what the program should do Look at all the details Make sure you understand the implication of each change before you make it Dont make arbitrary changes
SLIDE-157
Summary
1.
2. 3. 4. 5. 6. 7.
Design Methodologies Software Engineering Processes Software Development Phases Specification and Design Methodologies Implementation of Software Applications Software Failure Method Timing
Software Engineering, Sixth Edition by Roger Pressman Software Engineering Volume 1: The Development Process. IEEE Press.
UML Excerpts from http://pigseye.kennesaw.edu/~dbraun/csis4 650/A&D/UML_tutorial/activity.htm
Further Research Use Cases UML Diagrams Extreme Programming SDLC Waterfall Methodology Spiral Model Concurrent Development Model Aspect Oriented Software Development Agile Development Navigation Analysis Systems Theory
December 30, 2006
SLIDE-158
Java Arrays
An array is used to process a collection of data with the same data type. Examples List of test scores or temperatures List of names or addresses List of objects
Declaring and Creating an Array int score[] = new int[5]; Same As: int score1; int score2; int score3; int score4; int score5;
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-160
Java Arrays
Structured way to store many of similar typed variables or objects Index through the array starting with zero Arrays must be declared with some predetermined size Arrays can store numbers, strings and objects Arrays can be single dimension or multi dimension
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-161
Java Arrays
Array types are the second kind of reference types in Java. An array is an ordered collection, or numbered list, of values. The values can be primitive values, objects, or even other arrays, but all of the values in an array must be of the same type. The type of the array is the type of the values it holds, followed by the characters []. For example:
byte b; byte[] arrayOfBytes; byte[][] arrayOfArrayOfBytes; Point[] points; // // // // byte is a primitive type byte[] is an array of byte byte[][] is an array of byte[] Point[] is an array of Point objects
SLIDE-162
Declaring Arrays
Declaring and Creating an Array in Java
int junk[] float arr1[] char arr2[] string names[] = = = = new new new new int[200]; float[2000]; char[40]; string[20000];
JComboBox boxes[] = new JComboBox[25]; JMenuItems menuItems[] = new JMenuItems[50]; Object obj[] = new Object[61];
Getting the length of an array or array list
Arrays Array Lists Strings arr.length arr.size() arr.length()
SLIDE-163
Declaring Arrays
SLIDE-164
Declaring Arrays
Declaring a Java Array
int scores[] scores[5]; = new int[5]; // index out of bounds // Java compiler will not detect // causes runtime error
SLIDE-165
Java Arrays
int counts[5] = {2,4,6,8,10}; int i = 1000; for (i=0; i<=5; i++) counts[i]=0; // causes runtime error when i=5 // Throws ArrayIndexOutOfBoundsException
Before -
0th 2 0th 0
1st 4 1st 0
2nd 6 2nd 0
3rd 8 3rd 0
4th 10 4th 0
After -
SLIDE-166
Java Arrays
String[] responses = new String[2]; responses[0] = "Yes"; responses[1] = "No"; // Create an array of two strings // Set the first element of the array // Set the second element of the array
The fact that Java does all array initialization at runtime means that the elements of an array literal can be expressions that are computed at runtime:
Point[] points = { circle1.getCenterPoint(), circle2.getCenterPoint() };
SLIDE-167
Java Arrays
int[] perfectNumbers = {6, 28};
This is compiled into Java byte codes that are equivalent to:
int[] perfectNumbers perfectNumbers[0] perfectNumbers[1] = new int[2]; = 6; = 28;
So, if you want to include a large amount of data in a Java program, it may not be a good idea to include that data literally in an array, since the Java compiler has to create lots of Java byte codes to initialize the array, and then the Java interpreter has to execute all that initialization code
SLIDE-168
Multi-Dimensional Arrays
Type name[][]. . . . .
double accounts[][] = new accounts[5][50]; double weather[][][] = new weather[100][200][500]; int antenna[][][][] = new antenna[20][20][20][20]; if (antenna[5][6][z][w] == 100) . . .
SLIDE-169
Multi-Dimensional Arrays
int[][] products = { {0, {0, {0, {0, {0,
byte arrayOfBytes[]; byte arrayOfArrayOfBytes[][]; byte[] arrayOfArrayOfBytes[];
0, 1, 2, 3, 4,
0, 2, 4, 6, 8,
};
// Same as byte[] arrayOfBytes // Same as byte[][] arrayOfArrayOfBytes // Yuk! Same as byte[][] arrayOfArrayOfBytes
SLIDE-170
Multi-Dimensional Arrays
When you create a multidimensional array using the new keyword, you always get a rectangular array: one in which all the array values for a given dimension have the same size. This is perfect for rectangular data structures, such as matrixes. Because multidimensional arrays are implemented as arrays of arrays in Java, you are in no way constrained to use rectangular arrays. For example, since our multiplication table is symmetrical about the diagonal from top left to bottom right, we can represent the same information in a nonrectangular array with fewer elements:
int[][] products = { {0}, {0, 1}, {0, 2, 4}, {0, 3, 6, 9}, {0, 4, 8, 12, 16} };
SLIDE-171
Copying Arrays
SLIDE-172
Expanding an Array
double newData = new double[2 * data.length]; System.arraycopy(data, 0, newData, 0, data.length); data = newData;
SLIDE-173
SLIDE-174
ArrayList arr = new ArrayList(); arr.add( Dave ); arr.add( Tom ); arr.add( Steve ); arr.add(0, Sally ); arr.add(1, Danny );
// or you can use an index
SLIDE-175
SLIDE-176
SLIDE-177
SLIDE-178
SLIDE-180
SLIDE-181
SLIDE-182
Summary
Arrays Array Lists Vector Class Collection Class
Material extracted from: Data Structures and the Java Collections Framework, 2nd Ed. William Collins Data Structures and Other Objects, 2nd Ed. by Michael Main
SLIDE-183
Concepts of text and binary formats Read and write objects Sequential and random file access
Binary format is a series of bytes more efficient for the computer to process
00 00 48 57 in base-10 00 00 30 39 in hex 0000 0000 0000 0000 0011 0000 0011 1001
SLIDE-185
SLIDE-186
SLIDE-188
SLIDE-189
Streams access sequences of bytes Readers and writers access sequences of characters They process individual bytes and characters only Must use other classes and methods to process entire objects or lines of data
Use FileReader and FileWriter to read and write text files Use FileInputStream and FileOutputStream to read and write binary files
SLIDE-190
Common Error
Using the back slash in a file name
FileInputStream in = new FileInputStream(C:\\homework\\csc205\\pg1.java);
SLIDE-192
Common Error
Negative byte values
class Tester2 { public static void main(String[] args) { int n = 233; // binary 00000000 00000000 00000000 11101001 byte b = (byte) n; // binary 11101001, with sign bit set = -105 if (b != n) { System.out.println("Not Equal"); } System.out.println(n); System.out.println(b); } }
SLIDE-193
Object Streams
We can also read and write entire objects We use ObjectOutputStream and ObjectInputStream Objects are stored in binary format therefore we use streams not writers
Coin c = new Coin(); ObjectOutputStream out = new ObjectOutputStream(coins.dat); out.writeObject(c); Coin c = new Coin(); ObjectInputStream in = new ObjectInputStream(coins.dat); Coin c = in.readObject();
SLIDE-196
Random Access
Most data in the business world is comprised of records. Records are sets of related information
1. 2. 3. 4. 5. 6.
Databases contain sets of related files Files contain records Records contain fields Fields contain characters (bytes) Bytes are made up of bits Bits
Think of a File Cabinet (Database) Contains Drawers (Files) Contains Folders (Records) We generally want to gain access to specific records in an arbitrary manner. We introduce Random Access files
SLIDE-197
Random Access
So far we have simply used sequential access Reading bytes from start until we reach the end of a file Each file has a file pointer that points to the current position in the file Upon opening a file, the position is 0 RandomAccessFile is the random access class Works on fixed length records Can be a fixed length of one, if necessary
File Name File Mode
RandomAccessFile(bank.dat, rw); // moves file pointer to byte n // get current file pointer in n // get the file length in bytes
Copyright 2004-2007, Jim Adams SLIDE-198
Random Access
import java.io.*; class RandomAccess { public static void main(String[] args) throws IOException { long n; long filelength; byte ch; RandomAccessFile f = new RandomAccessFile("Tester.java", "r"); n = f.getFilePointer(); filelength=f.length(); // get current file pointer in n // get the file length in bytes
for (n=0; n<20; n++) { f.seek(n); ch = f.readByte(); // read a byte System.out.println((char) ch); } System.out.println(filelength); // display the file length } }
SLIDE-199
File Dialogs
JFileChooser Lets user navigate through their directories and select a file Relies on another class named File File inputfile = new File(input.txt); Key Elements
import java.io.*; import javax.swing.JFileChooser; JFileChooser chooser = new JFileChooser(); FileReader in = null; File selectedFile = chooser.getSelectedFile(); in = new FileReader(selectedFile);
SLIDE-200
File Dialogs
import java.io.*; import javax.swing.JFileChooser; class Tester4 { public static void main(String[] args) throws IOException { char ch; int next; boolean done=false; String inputline; JFileChooser chooser = new JFileChooser(); FileReader in = null; if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); in = new FileReader(selectedFile); } while (!done) { next = in.read(); if (next == -1) done=true; else { ch = (char) next; System.out.print(ch); } }
Copyright 2004-2007, Jim Adams SLIDE-201
} // end of class
Streams use sequences of bytes Readers and writers access characters Use FileReader and FileWriter to access characters Use FileInputStream and FileOutputStream to access bytes Use JFileChooser to let the user select a file Random access can read and and write records A file pointer is a position in a random access file Sequential access files are process serially
SLIDE-202
Students learn best when they practice every day and when they teach others
Recursion Programming
What it is How to do it Examples
Introduction
o
Recursion is a powerful programming technique that provides elegant solutions to certain problems. Recursion is a programming technique in which a method calls itself either directly, or indirectly through another method. Where is recursion used?
o o o o o
File and Directory Searches Traveling Salesman Problems Shortest Route Problems Mathematical Series Types of Problems Sorting and Searching
SLIDE-204
Overview
o
AT ONE TIME OR ANOTHER, you've probably been told that you can't define something in terms of itself. Nevertheless, if it's done right, defining something at least partially in terms of itself can be a very powerful technique. A recursive definition is one that uses the concept or thing that is being defined as part of the definition. An "ancestor" is either a parent or an ancestor of a parent. A "sentence" can be, among other things, two sentences joined by a conjunction such as "and." A "directory" is a part of a disk drive that can hold files and directories. In mathematics, a "set" is a collection of elements, which can be other sets. A "statement" in Java can be a while statement, which is made up of the word "while", a boolean-valued condition, and a statement.
SLIDE-205
o o
o o
Simple Example 1
public static void main(String[] args) { myMethod1(20); } static void myMethod1(int counter) { if(counter == 0) return; else { System.out.println(counter); myMethod1(--counter); return; } } // end myMethod }
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
SLIDE-206
Simple Example 2
public static void main(String[] args) { myMethod2(20); } static void myMethod2( int counter) { if(counter == 0) return; else { System.out.println("hello" + counter); myMethod2(--counter); System.out.println(goodbye + counter); return; } } // end of method } // end of main
December 30, 2006 Copyright 2004-2007, Jim Adams
hello20 hello19 hello18 hello17 hello16 hello15 hello14 hello13 hello12 hello11 hello10 hello9 hello8 hello7 hello6 hello5 hello4 hello3 hello2 hello1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
SLIDE-207
Mathematical formulas often are expressed recursively. In the following example, we will look in depth at factorials.
SLIDE-208
Definition of Factorial
Factorials - ! The symbol for factorial is ! - the exclamation mark. The factorial of a positive integer is the product of all nonnegative integers less than or equal to that number. Zero factorial is a special case and 0! = 1 From this definition, 5! is 120. 5! = 5 . 4 . 3 . 2 . 1 = 120 This formula often is defined recursively, for all nonnegative integers as: n! = n(n-1)! for n > 0; 0! = 1; Any number factorial is that number times the factorial of one less than that number.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-209
A Closer Look
Now, lets look at the expression,
n! = n * (n-1)! for n > 0; 0! = 1
You will notice that n! subtracts 1 from n, then recomputes the factorial of n-1. This is the recursion. Also notice that the simplest case is 0! This is called the base case.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-210
Base Cases
Base cases are important. A recursive method can solve only a base case. If the method is called with a base case, it returns a result. If the methods is called with something other than the base case, the recursive method will decide what part it can accomplish, and then call itself to solve the rest of the problem.
o o
SLIDE-212
Linear Recursion
o
Linear recursion is the simplest form of recursion. It occurs where an action has a simple repetitive structure consisting of some basic step followed by the action again.
procedure ODSN begin One dark and stormy night, Three men sat in a cave, And one said to another, Dick, tell us a tale, And this is how the tale began: ODSN -- again! end
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-213
Linear Recursion
This simple tale has amused generations of small children precisely because it is so simple but never ends. It seems somehow paradoxical. Generally we want the recursion to terminate on some condition. The song `Ten Green Bottles' does not go on forever:
SLIDE-214
Linear Recursion
Ten Green Bottles
10 green bottles hanging on the wall, 10 green bottles hanging on the wall, And if 1 green bottle should accidentally fall, There'll be 9 green bottles hanging on the wall. 9 green bottles hanging on the wall, 9 green bottles hanging on the wall, And if 1 green bottle should accidentally fall, There'll be 8 green bottles hanging on the wall. .... 2 green bottles hanging on the wall, 2 green bottles hanging on the wall, And if 1 green bottle should accidentally fall, There'll be 1 green bottle hanging on the wall. 1 green bottle hanging on the wall, 1 green bottle hanging on the wall, And if 1 green bottle should accidentally fall, There'll be 0 green bottles hanging on the wall.
SLIDE-215
Linear Recursion
This illustrates the power of recursion nicely. The routine worries not so much about the whole song as about the basic step, one verse. It calls itself to generate the rest of the song. Note the terminating condition, i.e. the base case (n<=0) and test for it. The parameter `n' is decreasing in the recursive calls `verse(n-1)' so eventually n reaches zero, and the program terminates.
SLIDE-216
Recursion
o
SLIDE-217
Binary Searching
static int binarySearch(int[] A, int loIndex, int hiIndex, int value) { // Search in the array A in positions from loIndex to hiIndex, // inclusive, for the specified value. It is assumed that the // array is sorted into increasing order. If the value is // found, return the index in the array where it occurs. // If the value is not found, return -1. if (loIndex > hiIndex) { // The starting position comes after the final index, // so there are actually no elements in the specified // range. The value does not occur in this empty list! return -1; } else { // Look at the middle position in the list. If the // value occurs at that position, return that position. // Otherwise, search recursively in either the first // half or the second half of the list. int middle = (loIndex + hiIndex) / 2; if (value == A[middle]) return middle; else if (value < A[middle]) return binarySearch(A, loIndex, middle - 1, value); else // value must be > A[middle] return binarySearch(A, middle + 1, hiIndex, value); } } // end binarySearch()
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-218
Pascals Triangle
for(int i=0; i< 10; i++) { for(int j=0; j <=i; j++) System.out.println(); }
1 11 121 14641 1 5 10 10 5 1 1 6 15 20 15 6 1
System.out.print(pascal(i,j)+" "); 1 3 3 1
public static long pascal (int n, int k) 1 7 21 35 35 21 7 1 { if (k == 0 || k == n) return 1; else return pascal(n-1,k-1) + pascal(n-1,k); }
December 30, 2006 Copyright 2004-2007, Jim Adams
1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1
SLIDE-220
Reverse a String
public static void ReverseString(String s) { if (s.length() == 1) System.out.print(s); else { ReverseString(s.substring(1)); System.out.print(s.charAt(0)); } }
SLIDE-221
Summary
o
Recursion is a powerful programming technique that provides elegant solutions to certain problems. Recursion is a technique in which a method calls itself either directly, or indirectly through another method. Base cases are usually the simplest cases a recursive method can solve. Recursion is Difficult to Master Recursion yields elegant and concise code Yet, it is difficult to debug
o o o
SLIDE-222
Linked Lists
A linked list consists of a number of links, each of which has a reference to the next link Adding and removing elements in the middle of a linked list is efficient Visiting the elements of a linked list in sequential order is efficient Random access is not efficient
SLIDE-225
Linked Lists
Some common examples of a linked list: Hash tables use linked lists for collision resolution Any "File Requester" dialog uses a linked list Binary Trees Stacks and Queues can be implemented with a doubly linked list Relational Databases
SLIDE-226
1. 2.
Each object points to the next one Each object points to the previous one, as well
SLIDE-227
1. 2. 3.
Get the address of both sides of the location you want to add Allocate a new object Adjust the pointers
SLIDE-228
1. 2.
SLIDE-229
SLIDE-230
2.
SLIDE-231
Node p = node; while (p != null) { System.out.println(p.value + " | " + p.next); p = p.next; } Node h = head; System.out.println("Head Value:" + h.value); System.out.println("Head Pointer:" + h.next);
SLIDE-233
SLIDE-234
public class Node { private int value; // value of element private Node next; // reference to next node public Node(int value_in, Node n) { this.value = value_in; this.next = n; }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-235
SLIDE-236
SLIDE-237
Iterator Interface
The Iterator Interface gives access to elements inside a linked list Used for moving forward through a linked list
LinkedList list = new LinkedList(); Iterator iterator = list.iterator();
SLIDE-240
List Iterator
The next method moves the iterator iterator.next(); next method throws a NoSuchElementException if you are already past the end of the list The hasNext method returns true if there is a next element if (iterator.hasNext()) iterator.next();
SLIDE-241
List Iterator
The next method returns the object of the link that it is passing
while (iterator.hasNext()) { Object obj = iterator.next(); //do something with the object }
SLIDE-242
List Iterator
To move the list position backwards, use:
hasPrevious previous
while (iterator.hasPrevious()) { Object obj = iterator.previous(); //do something with the object }
SLIDE-243
SLIDE-244
SLIDE-245
Adding a New First Element When a new link is added to the list using the addFirst() method
It becomes the head of the list The old first link becomes the next link
SLIDE-246
SLIDE-247
SLIDE-249
public class LinkList { private String[] names = {"Jamie", "Suzie", "Callie", "Malcholm", "Danny", "Dan", "Roger", "Eric", "Mike", "Will", "Carolyn"}; public LinkList() { LinkedList staff = new LinkedList(); // add a bunch of string objects to the end for (int i = 0; i < names.length; i++) { staff.addLast(names[i]); } // add some string objects to the front staff.addFirst("Sharon"); staff.addFirst("George"); staff.addFirst("Patty"); staff.removeFirst(); staff.removeLast(); printIndexes(staff); printBirthOrder(staff); printReverseOrder(staff);
SLIDE-250
private void printReverseOrder(LinkedList list) { System.out.println("Printing in reverse birth order"); list.getLast(); ListIterator iterator = list.listIterator(); while (iterator.hasPrevious()) { System.out.println(iterator.previous()); } }
SLIDE-251
SLIDE-252
SLIDE-254
Summary
1. 2. 3.
SLIDE-255
Stacks Queues
SLIDE-257
SLIDE-258
Always either Adding the First object or Deleting the First Object Called Push and Pop Push one on the stack Pop one off the stack
SLIDE-259
Stacks are used by the hundreds in computer science, especially operating systems Internal stacks are used to control the return address of method calls
SLIDE-260
Stack Discussion
java.lang.Object java.util.AbstractCollection java.util.AbstractList java.util.Vector java.util.Stack Methods of the Java Stack Class boolean empty() Object peek() Object pop() Object push(Object) int search(Object) Returns true if stack is empty Gets the top object, but does not remove it Removes the top object Adds a new object to the top of the stack Gets the position of an object
SLIDE-261
System.out.println("Stack Size is:" + s.size()); try { while(true) System.out.println(s.pop()); } catch (Exception ex) { System.out.println("Whoops. Stack is Empty, Baby"); }
SLIDE-262
SLIDE-263
SLIDE-264
Harry Stack Size is Now:8 Charlie is at Location:6 1:Harry 2:Gamma 3:Frank 4:Epsilon 5:Delta 6:Charlie 7:Beta 8:Alpha
System.out.println(s.peek()); // look at top value int stack_size=s.size(); System.out.println("Stack Size is Now:" + stack_size); // look at size int loc = s.search("Charlie"); System.out.println("Charlie is at Location:" + loc); int n=1; while (! s.empty()) System.out.println(n++ + ":" + s.pop()); } }
SLIDE-265
import java.util.LinkedList; import java.util.ListIterator; import java.util.NoSuchElementException; public class Stack { static LinkedList staff = new LinkedList(); static ListIterator iterator = staff.listIterator(); public static void main(String[] args) { String name; int i; push("Jamie"); push("Suzzy"); push("Callie"); push("Malcholm"); push("Dan"); push("Will"); push("Roger"); push("Eric"); push("Mike"); push("Sharon"); push("George"); push("Patty"); for (i=0; i<15; i++) System.out.println(pop());
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-266
Stack Simulation (1 of 2)
Stack Simulation (2 of 2)
// Push an object onto the stack // Passes a string object to place onto the stack // private static void push(String p) { staff.addFirst(p); } // Pop an object off of the stack // Returns a string object from the stack George Sharon // Mike private static String pop() { Eric Object obj=null; Roger String name=""; Will if (iterator.hasNext()) { obj=staff.getFirst(); name = (String) obj; staff.removeFirst(); return(name); } else //throw new NoSuchElementException(); return("End of Stack"); } // end of method
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-267
Patty
Dan Malcholm Callie Suzzy Jamie End of Stack End of Stack End of Stack
Expression Parsing
One place where stacks can be useful is in parsing expressions like,
x = {[X+Y*(Z+7)]*(A+B)}
One could write a Java method that returns a boolean
balanced = isBalanced(expression);
Each left brace, parenthesis or bracket causes a push onto a stack structure Each right occurrence causes a pop off the stack.
SLIDE-268
Expression Parsing
Using the previous good expression,
x = {[X+Y*(Z+7)]*(A+B)}
we would be doing the following: 1. Push { 2. Push [ 3. Push ( 4. Pop ) 5. Pop ] 6. Push ( 7. Pop ) 8. Pop } Empty Stack means we are balanced
SLIDE-269
Expression Parsing
Using the following bad expression,
x = {[X+Y*(Z+7)*(A+B)}
we would be doing the following: 1. Push { 2. Push [ 3. Push ( 4. Pop ) 5. Push ( 6. Pop ) 7. Pop } The Stack is not empty so we must be unbalanced In other words we left something on the stack
SLIDE-270
Expression Parsing
Let's look at this fully parenthesized expression, double x = (((6+9)/3)*(6-4)); We need to extract the leftmost of the innermost subexpression (((6+9)/3)*(6-4)) ((15/3)*(6-4)) (5*(6-4)) (5*2) 10 This method works well with paper and pencil, but how do we extract each character?
SLIDE-271
Expression Parsing
We need two stacks to parse an expression
1. 2.
We read up to the first right parenthesis; the numbers we encounter along the way are pushed onto the number stack Operators we encounter along the way are pushed onto the operator stack double x = (((6+9)/3)*(6-4)); When we reach the first right parenthesis we have the following stack situation
9 6
Number Stack
+
Op Stack
SLIDE-272
Expression Parsing
Whenever we reach a right parenthesis, we combine the top two numbers on the number stack, using the topmost operator on the operator stack double x = (((6+9)/3)*(6-4)); In our example we combine 6 + 9 to get 15 and push that value onto the number stack, and pop one off the op stack
15
Number Stack Op Stack
/
Op Stack
SLIDE-273
Expression Parsing
We combine 15 / 3 to get 5 and push that value onto the number stack Our expression now looks like: (5*(6-4))
5
Number Stack Op Stack
We parse out the next two numbers, 6 and 4 and push them onto the number stack Push the minus sign onto the operator stack
4 6 5
Number Stack
*
Op Stack
SLIDE-274
Expression Parsing
We combine 6 - 4 to get 2 and push that value onto the number stack Our expression now looks like: (5*2)
2 5
Number Stack
*
Op Stack
Finally, we pop the last two numbers off the stack along with the last operator. Combine them and push the final values back on to the stack
10
Number Stack Op Stack
SLIDE-275
Expression Parsing
Issues
(((6+9)/3)*(6-4)); ( ( ( 6 + 9) / 3 ) * ( 6 - 4) ); (((x+y)/q)*(6-w)); ( ( ( x + y) / q ) * ( 6 - w) ); ((( x + y) / q ) * (6 pow(w))); // // // // // numbers only are easy white space variables variables & white space embedded methods
SLIDE-276
A Queue
SLIDE-277
Indirect applications Auxiliary data structure for algorithms Component of other data structures
SLIDE-278
SLIDE-279
SLIDE-280
Always either Adding the First object or Deleting the Last Object Like the Check-out Lines at the Home Depot
SLIDE-281
Java is excellent for simulation of queued processes Supermarket checkout lines Printer queues on LANs The list is almost endless Point to consider: 1. Create a Java class with two threads 2. Thread-1 generates a random number used as a timer and pushes an object onto a queue structure. Much the same as people arriving at a check-out counter at Albertsons 3. Thread-2 pops an object off the other end at random intervals based on constraints dictated by the store or queuing process in question. For example, there is more than likely a minimum time for checking out. 4. Let the Java class run for a long period of time and generate metrics based on the queue length and service times.
SLIDE-282
Priority Queue (1 of 3)
public class Priority_Queue { LinkedList staff = new LinkedList(); ListIterator iterator = staff.listIterator(); String[] names = {"Jamie", "SuzyQ", "Jamie", "Sally", "Callie", "Celest", "Malcholm", "Goofy", "Daffy", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Kristy", "Patty", "Lindsey"}; public Priority_Queue() { int i = 1; String entry = ""; int key = 0; Random rand = new Random(); for (i = 0; i < names.length; i++) { key = rand.nextInt(9) + 1; entry = key + names[i]; addone(entry); } dump(); }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-283
Priority Queue (2 of 3)
private void addone(String passed_name) Object obj = null; String name = ""; int comp = 0; { iterator = staff.listIterator(); if (iterator.hasNext()) { obj = staff.getFirst(); name = (String) obj; comp = name.compareTo(passed_name); //is the existing name greater that the one being passed? //if so, add the passed name to the beginning of the list if (comp > 0) { System.out.println("Adding to First " + passed_name); staff.addFirst(passed_name); return; } else { // loop through the linked list looking for the element higher // than the one we are inserting do { obj = iterator.next(); name = (String) obj; comp = name.compareTo(passed_name); } while (iterator.hasNext() && comp <= 0); // handle special circumstance here if (comp > 0) { iterator.previous(); } System.out.println("Adding This:" + passed_name); iterator.add(passed_name); } } else { System.out.println("Adding To a Null List:" + passed_name); staff.addFirst(passed_name); } // end of outer if
SLIDE-284
Priority Queue (3 of 3)
private void dump() { iterator = staff.listIterator(); System.out.println("\n\n\nSorted List"); while (iterator.hasNext()) { System.out.println(iterator.next()); } } // end of method
Run Output
Adding To a Null List:3Jamie Adding to First 2SuzyQ Adding This:7Jamie Adding to First 2Sally Adding to First 2Callie Adding This:2Celest Adding This:9Malcholm Adding This:4Goofy Adding This:7Daffy Adding This:7Eric Adding This:5George Adding This:6Sharon Adding This:2Carolyn Adding This:7Jim Adding This:5Danny Adding This:6Roger Adding This:6Will Adding This:4Gina Adding This:6Kristy Adding This:9Patty Adding This:8Lindsey
Sorted List 2Callie 2Carolyn 2Celest 2Sally 2SuzyQ 3Jamie 4Gina 4Goofy 5Danny 5George 6Kristy 6Roger 6Sharon 6Will 7Daffy 7Eric 7Jamie 7Jim 8Lindsey 9Malcholm 9Patty
SLIDE-285
SLIDE-286
SLIDE-287
SLIDE-288
PriorityBlockingQueue q = new PriorityBlockingQueue(); for (int i=0; i<10000; i++) q.add(getRandomString()); // 4-byte strings System.out.println(q.size()); String s; try { s = (String) q.take(); System.out.println(s); } catch (InterruptedException ex) { ex.printStackTrace(); }
SLIDE-289
1. 2. 3. 4. 5. 6.
SLIDE-290
SLIDE-292
Sorting
Many types of sorting algorithms Hash Insertion Bubble Sorting and Sort Systems Selection by Harold Lorin. Shell We will focus on Tournament Shaker Selection Sort Quick Sort Merge Sort Exchange Quick Sort Poly-Phase Cascade Bubble Sort Oscillating Crisscross Merge
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-293
Getting Ready
Before we start you will need some utility routines inside a utility class
Loader A constructor or a method to declare an array of some size and load it with random data generally integers for these tests Dumper A method to display the final sorted result, or perhaps the original data. Call the dump method passing it an array object Timer A method to get the system in milliseconds so you can time the algorithms
SLIDE-294
Selection Sort
Selection Sort Algorithm
1.
2.
3.
4. 5. 6.
Starting at the 0th element, search for the smallest element in the set 0 through n. Exchange with the 0th element Starting at element-1, search for the smallest element in the range 1 through n. When found, exchange with element-1 Starting at element-2, search for the smallest in 2 through n. Exchange with the 2nd element Starting at element-3, search for the smallest in 3 through n. Exchange with the 3rd element Continue until the nth element is reached Java Methods Needed
1. 2.
Search Swap
SLIDE-295
Selection Sort
Selection Sort Discussion
Methods
1. 2.
Search for the lowest element starting from nth element Swap the lowest element with nth element
SLIDE-296
Merge Sort
Merge Sort Algorithm-1 (Sorted Data)
1. 2. 3. 4. 5. 6. 7. 8.
Arrays should be sorted prior to merge Start at the beginning of each array, n Test both arrays elements, n Take the lower of the two and move to a new array Get the next element, n+1, in both arrays Test both arrays elements, n Take the lower of the two and move to a new array Continue until there is no more data
Array1
Array2
Arrays need NOT be sorted prior to merge Search each array for the lowest value, n and m Test both values n and m Take the lower of the two values and move to a new array Change the lowest value in the original arrays to MAX_VALUE so as not to select again Search each array for the lowest value, n and m Test both values n and m Take the lower of the two and move to a new array
SLIDE-297
Merge Sort
Merge Sort Discussion
1. 2. 3.
4.
5.
1.
Needs a third array to hold the sorted data More complex than Selection sort in that you need to check for sorted-ness, OR The input arrays dont need to be sorted but if they arent then you need to search each input array for the smallest element for each pass Merge sort is an n(log(n)) algorithm which grows more slowly that an n2 algorithm Methods
2. 3. 4.
Array1
Array2
Search for the Lowest Element Get an Element Put Element to the new array Mark the Lowest so we dont pick again
SLIDE-298
Compare element-0 with element-1 If element-0 is greater than element-1, then swap the two elements Continue on with element-1 and element-2 Continue on with element-2 and element-3 Elements are known as element n and element n+1 Continue until the end of the array is reached Repeat steps 1 through 6 until no swaps are made This algorithm is known as an n2 algorithm On an array of 10 it could take as many as 100 swaps
SLIDE-299
4. 5.
There are ways to speed up the bubble sort Inside the inner loop, test to see if you swapped anything If no swaps were made the sort is finished. This will usually cut the sort time in half unless the data is reversed from the start Bubble sort is an n2 algorithm Methods
1. 2.
SLIDE-300
Shaker Sort
Shaker Sort Algorithm Discussion
1. 2.
3.
A Shaker Sort is bi-directional bubble sort because we work from both ends Alternate movements between 0 and n on one pass to n and 0 on the next pass. This will move an element right to the top or bottom depending on which way you are moving. It gets its name because of the way it moves about the list, back and forth like a salt shaker or the popular beverage mixer. http://users.net1plus.com/brianl/ShakerSort.htm
4.
SLIDE-301
Insertion Sort
Insertion Sort Algorithm 1. Declare a second array the same size as the original 2. Read the original array sequentially 3. Insert each element one at a time into the new array 4. Must search for the insertion point and adjust the array contents upwards each time 5. Methods 1. Search 2. Insert 3. Bump Up
December 30, 2006
First Pass
24 12 1 19 32 6 54 9 14 24 1 34 23 33 7 34 Move the 1st to the 1st 24
SLIDE-302
Insertion Sort
SLIDE-303
Quick Sort
Quick Sort Algorithm
1. 2. 3.
If there are one or less elements in the array to be sorted, return immediately. Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.) Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot. Recursively repeat the algorithm for both halves of the original array.
4.
SLIDE-304
Quick Sort
Quick Sort Pseudocode
int function Partition (Array A, int Lb, int Ub) begin
select a pivot from A[Lb]A[Ub]; reorder A[Lb]A[Ub] such that: all values to the left of the pivot are pivot all values to the right of the pivot are pivot return pivot position;
end; procedure QuickSort (Array A, int Lb, int Ub) begin if Lb < Ub then M = Partition (A, Lb, Ub); QuickSort (A, Lb, M 1); QuickSort (A, M, Ub); end;
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-305
Quick Sort
Quick Sort Discussion
The quick sort is an in-place, divide-and-conquer, recursive sort. The quick sort algorithm is simple in theory, but very difficult to put into code The recursive algorithm consists of four steps which closely resemble the merge sort:
1. 2. 3. 4.
If there are one or less elements in the array to be sorted, return immediately. Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.) Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot. Recursively repeat the algorithm for both halves of the original array.
The efficiency of the algorithm is impacted by which element is chosen as the pivot point. The worst-case efficiency of the quick sort, O(n2), occurs when the list is sorted and the left-most element is chosen. As long as the pivot point is chosen randomly, the quick sort has an algorithmic complexity of O(n log n).
SLIDE-306
Generated Output
643 675 469 993 45 496 815 646 317 892 187 793 858 587 859 380 809 871 639 331 0 0 0 1 1 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-307
Sort Animation Web Site Demonstration of Selection, Bubble, Insertion, Heap, Merge and Quick Sorts
http://www.ship.edu/~cawell/Sorting/selintro.htm
SLIDE-308
Selection Sort (1 of 2)
iterations; a;
View Problem 4
// Primary constructor public SelectionSort(int[] anArray) { a = anArray; iterations=0; } // Main Sort Routine // public void sort() { int i=0; for (i = 0; i<a.length-1; i++) { int minPos = getMinimumPosition(i); swap(minPos, i); iterations++; } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-309
Selection Sort (2 of 2)
// Get the element with the minimum value private int getMinimumPosition(int from) { int minPos = from; for (int i = from + 1; i < a.length; i++) if (a[i] < a[minPos]) minPos = i; return minPos;
// swap the minimum with the pivot element private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public void display() { System.out.println ("Iterations:" + iterations); } } // end of class
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-310
Generated Output
802 758 285 476 226 328 317 435 267 246 451 79 799 543 629 928 914 900 909 483 79 226 246 267 285 317 328 435 451 476 483 543 629 758 799 802 900 909 914 928 Iterations:19
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-311
Array Utility (1 of 3)
import java.util.Random; public class ArrayUtil { private long elapsedTime=0; private long startTime=0; private long endTime=0; // // Create an array of random integers // Passed array size and max value // public int[] createArray(int length, int n) { int[] a = new int[length]; Random generator = new Random(); for (int i = 0; i < a.length; i++) a[i] = generator.nextInt(n); } return a;
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-312
Array Utility (2 of 3)
// // Print 50 bytes of the passed integer array // public void print(int[] a) { int arrlen=0; if (a.length>50) arrlen=50; else arrlen=a.length; for (int i = 0; i < arrlen; i++) System.out.print(a[i] + " "); } System.out.println();
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-313
Array Utility (3 of 3)
// // Start the internal timer // public void startTimer() { startTime=System.currentTimeMillis(); } // // Stop the internal timer // public void stopTimer() { endTime=System.currentTimeMillis(); } // // Get the elapsed time // public long getElapsedTime() { elapsedTime=endTime-startTime; return(elapsedTime); } } // end of class
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-314
The bubble sort is an n2 algorithm Array of 20, worst case is 400 iterations (20x20) Generated output:
814 763 628 550 564 862 104 245 579 713 11 460 321 113 647 74 389 607 65 602 11 65 74 104 113 245 321 389 460 550 564 579 602 607 628 647 713 763 814 862
Iterations:124
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-315
Discussion Points
Sorting
1. What if there is negative numeric data in the sort sequence? 2. In a merge sort what happens if one array is exhausted first? 3. What about other data types? (Strings, Objects) 4. What about mixed data types 5. What about sorting a data file with millions of records? 6. Where do you keep the temporary data? Swap files? 7. What about sorting many data files with millions of records? 8. What about sorting various pieces of data within a record, say, name and SSN inside a record of dozens of other fields? 9. SORT3 sort utility @SORT filein,filein,filein,filein,etc KEY,1,23,9,A KEY,2,1,6,D DATA,17,6,COPY OPTIONS,MULTIKEY END
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-316
Summary
Sorting
References for this Section Malik, D. and Nair, S. (2003). Data Structures using Java. Thomson Press. Main, Michael. (2003). Data Structures and Other Objects using Java. AddisonWesley. Horstmann, Cay. (2006). Big Java. 2nd Edition. John Wiley & Sons. Goodrich, Michael T. and Tamassia, Roberto. (2004). Data Structures and Algorithms in Java. John Wiley & Sons.
SLIDE-317
Searching Algorithms
How we will cover the material in this chapter
1. 2. 3.
SLIDE-319
Searching an Array Picture a phonebook How would you find a number by name? How would you find a name by using a number? Linear Search
Search linearly Start at the beginning and test every occurrence Sort the data Successive slicing in half
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-320
Search alphabetically
Binary Search
Searching an Array of Integers If an array is not sorted, there is no better algorithm than a linear search for finding an element in it
public int linearSearch(int target, int[] a) { for (int i = 0; i < a.length; i++) { if (target == a[i]) return(i); } return(-1); // not a legal index }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-321
Searching an Array
Average Case Time
Say we have an array of 10 integers like 1,2,3,4,5,6,7,8,9,10 If we are searching for 1 then it takes one array access (hit) If we are searching for 10, then it takes 10 hits On average then, all searches take 1+2+3+4+5+6+7+8+9+10 = 5.5 10 We can generalize to
Average Case Time for Serial Search = (n + 1)/2
SLIDE-322
Searching an Array
Worst Case Time
The worst case time for a serial search is a "No Find" condition where we touch every element of the array
SLIDE-323
Binary Search
Say we have 100 million phone numbers Sort the numbers If we are looking for 555-480-9400 To see how many tests we need we need to use logarithms
Searches = log2x, where x is the total number of items Searches = log2100000000 for example How to solve: Searches = Log10100000000 / Log102 Searches = 8 / 0.301029996 Searches = 26.57 or rounded up to 27
From Log conversion formula (Applied Mathematics, p 1.6)
logb(x) = loga(x)/loga(b)
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-324
Binary Search
1. 2. 3.
First, sort the data (This could take some time) Say, we are searching for the number 401 Successively cut the array of data in half
Num(0) Num(1) Num(2) Num(3) Num(4) Num(5) Num(6) Num(7) Num(8) Num(9) Num(10) Num(11) Num(12) Num(13) Num(14) Num(15) Num(16) Num(17) 204 222 303 313 333 367 401 421 444 490 491 502 554 578 590 600 603 627
Middle Position
SLIDE-325
Binary Search
1.
2.
3.
If true, then discard the lower half, else discard the upper half
204 222 303 313 333 367 401 421 444 490 491 502 554 578 590 600 603 627
Middle Position
SLIDE-326
Binary Search
1. 2. 3. 4. 5. 6. 7. 8.
Test the middle element with the search value If (401 > 333) If true, then discard the lower half, else discard the upper half Find the middle position, again Test the middle element with the search value If (401 > 303) If true, then discard the lower half, else discard the upper half You keep slicing in half until you get to the element being sought
Middle Position
SLIDE-327
Binary Search
The method call for the binary search looks like this search(a, s, n, t); a is the array to search s is the starting element n is the number of elements to search t is the target The first time you call search use 0 for the start and the array length as the length If the target is found the method returns the index otherwise it returns -1 indicating a no find condition search(int[] int first, int size, int target)
SLIDE-328
Binary Search
Code Design
if (size <=0) return (-1) else { middle = index of the midpoint of the array segment if (target == a[middle]) the target value has been found at the midpoint else if (target < a[middle]) search for the target before the midpoint else if (target > a[middle]) search for the target after the midpoint }
SLIDE-329
Binary Search
Worst Case for Binary Search O(log n) Average Time is also O(log n) Generally a recursive method
SLIDE-330
} }
SLIDE-331
// // Main Logic for Binary Search // public int search(int[] a, int left, int right, int target) { while (left < right) { int middle = (left + right) / 2; if (a[middle] == target) return middle ; // found else if (a[middle] > target) right = middle - 1; else left = middle + 1; } return -1; // returning -1 means "not found" } } // end of class
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-332
SLIDE-333
Open-Address Hashing
Say, we sell tractors that have stock numbers ranging 0 to 49 We could easily have an array of 50 objects to hold each tractor object Tractor[ ] data = new Tractor[50]; But what if the stock numbers are not ranged from 0 through 49. Maybe they are 0, 100, 200, 300, 400, etc What if they are W129, T900, A123, etc
SLIDE-334
Open-Address Hashing
With keys like W129, T900, A123, etc We can compute a hash code Java has a built-in hash function or we could write our own hash function If the key is numeric, we can generally use modulo division to get a key Modulo division returns a remainder from 0 to n-1 of the number being divided Example rem = x % n gives us a number between 0 and n-1
0 = 800 % 10 1 = 601 % 10
SLIDE-335
SLIDE-336
Open-Address Hashing
Collisions Many times an object will hash to the same address This is called collision How do we handle collisions?
Two approaches:
Open-addressing Chaining
SLIDE-337
Open-Address Hashing
Simplest open address approach is linear probing If (index == hash(key)) is not empty, try index+1, then index+2, , until empty slot Note: searching for first open address leads to primary clusters collisions bunch up Quadratic probing vary probe, like 1, 3, 6, Leads to secondary clusters but not as quickly Or completely different approach chaining
SLIDE-338
Open-Address Hashing
Store all elements in table If a cell is occupied, try another cell. Linear probing, try cells
k A B C D E F G H I J K 53 41 91 75 13 6 43 67 88 36 40 H(k) 53 mod 17 = 2 2 7 6 7 13 6 7 16 3 2 6
41 mod 17 = 7
0 1 2 3 4 5 6 7 8 9
H(k) = k mod 17
10 11 12 13 14 15 16
SLIDE-339
Open-Address Hashing
Lookup (K) { p = HashKey(K); loop { if (A[p] is empty) return false; if (A[p] == K) return true; p = (p + 1) mod m; } }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-340
Chaining
We could use sets or array lists or linked lists attached to each hash address Constructor allocates memory for Array List, and creates an empty list for each element of the array
put method uses hash(key) and appends to end of list at that index of array Still should resize when load factor approaches 80%
SLIDE-341
Chaining
0: 1: null 2: 3: null 4:
Hash maps to a key value, 0,1,2, etc Collisions chain out from each key
We could use sets or array lists or linked lists attached to each hash address
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-342
Indexed Files
1. 2. 3. 4. An Indexed File has two, or more, parts Data is kept in the Data Part in Birth Order A separate file of keys is maintained for each key field Sometimes there can be several key files Data Part
SLIDE-343
Summary
1. 2. 3. 4. Linear Search Binary Search Open Address Hashing Chaining
Sets Hash Sets Hash Algorithms Maps Trees Tree Sets Binary Trees
SLIDE-346
Sets
An unordered collection of distinct elements is called a set Elements can be added, located, removed Sets do NOT have duplicates
Adding a duplicate is ignored
SLIDE-348
Hash Sets
Hash Sets are not sorted Hashing can be used to find elements in a data structure quickly without making a linear search A hash function computes an integer value (called the hash code) from an object A good hash function minimizes collisions, identical hash codes for different objects To compute the hash code of object x: int h = x.hashcode()
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-349
Hash Sets
Inheritance Diagram java.lang.Object java.util.AbstractCollection java.util.AbstractSet java.util.HashSet
SLIDE-350
Hash Sets
To implement
Generate hash codes for objects Make an array or other data structure Insert each object at the location of its hash code
SLIDE-351
Hash Sets
Take Account Numbers for Example. If you do a mod 10 division and capture the remainder, each Account maps to a different value less than 10. These remainder values can be sets.
87321 87327 87333 87339 87345 87351 87357 87363 87369 87375 87381 87387 87393 87399 87405 87411 87417 87423 87429 87435 87441 87447 87453 87459 87465 87471 87477 87483 87489 87495 87501 87507 87513 87519 87525 87531 87537 87543 87549 87555 87561 87567 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7 3 9 5 1 7
SLIDE-352
It is not possible to allocate an array that is large enough to hold all possible integer index positions It is possible for two different objects to have the same hash code
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-353
SLIDE-354
SLIDE-355
SLIDE-356
SLIDE-357
SLIDE-358
SLIDE-359
SLIDE-360
public class HashSet_Example { public HashSet_Example() { boolean goodAdd=false; String[] arr1 = {"Jamie", "SuzyQ", "Jamie", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Eric", "Kristy"}; int i = 1; Set names = new HashSet(); System.out.println("Original Length:" + arr1.length); { goodAdd = names.add(arr1[i]); if (! goodAdd) System.out.println("Whoops. Duplicate:" + arr1[i]); } display_set(names); names.remove("Eric"); names.remove("Jamie"); display_set(names);
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-362
Original Length:18 Whoops. Duplicate: Jamie Whoops. Duplicate: Eric Size:16 Set Contents Kristy Jamie Callie Celest Eric Sally Carolyn George Jim SuzyQ Malcholm Roger Gina Will Danny Sharon Size:14 Set Contents Kristy Callie Celest Sally Carolyn George Jim SuzyQ Malcholm Roger Gina Will Danny Sharon
SLIDE-363
Tree Sets
Tree Sets store data in Sorted order Tree sets are fast
Inheritance Diagram java.lang.Object java.util.AbstractCollection java.util.AbstractSet java.util.TreeSet
SLIDE-364
Notice Sorted public class TreeSet_Example { Output public TreeSet_Example() { boolean goodAdd = false; String[] arr1 = { "Jamie", "SuzyQ", "Jamie", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Eric", "Kristy" }; int i = 1;
TreeSet names = new TreeSet(); System.out.println("Original Length:" + arr1.length); for (i = 0; i < arr1.length; i++) { goodAdd = names.add(arr1[i]); if (! goodAdd) // handles dups System.out.println("Whoops. Duplicate:" + arr1[i]); } Iterator iterator = names.iterator(); System.out.println("Current Size:" + names.size()); while (iterator.hasNext()) System.out.println(iterator.next()); } } December 30, 2006 Copyright 2004-2007, Jim Adams
Original Length:18 Whoops. Duplicate:Jamie Whoops. Duplicate:Eric Current Size:16 Callie Carolyn Celest Danny Eric George Gina Jamie Jim Kristy Malcholm Roger Sally Sharon SuzyQ Will
SLIDE-366
import java.util.*;
public class TreeSet_Example { public TreeSet_Example() { boolean goodAdd = false; boolean status = false; String[] arr1 = {"Jamie", "SuzyQ", "Jamie", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Eric", "Kristy"}; int i = 1; TreeSet names = new TreeSet(); System.out.println("Original Length:" + arr1.length); for (i = 0; i < arr1.length; i++) { goodAdd = names.add(arr1[i]); if (!goodAdd) System.out.println("Whoops. Duplicate:" + arr1[i]); } status = names.remove("Eric"); if (status) // handles no find condition System.out.println("Delete was Successful"); else System.out.println("Can't Find Selected Name:Eric"); status = names.remove("Lucy"); if (status) // handles no find condition System.out.println("Delete was Successful"); else System.out.println("Can't Find Selected Name:Lucy"); Iterator iterator = names.iterator(); System.out.println("Current Size:" + names.size()); while (iterator.hasNext()) System.out.println(iterator.next());
SLIDE-367
Maps
A map keeps associations between key and value objects Every key in a map has a unique value. A value may be associated with several keys Classes that realize the Map interface
HashMap TreeMap Inheritance Diagram for HashMap Inheritance Diagram for TreeMap java.lang.Object java.lang.Object java.util.AbstractMap java.util.AbstractMap java.util.TreeMap java.util.HashMap
SLIDE-368
Maps
A Map is a kind of generalized array Like an array, a map is defined by "get" and "put" operations. In a map, these operations are defined not for integers 0, 1, ..., N-1, but for arbitrary Objects Some languages use the term associative array instead of "map" and use the same notation for associative arrays as for regular arrays In those languages, for example, you might see the notation A["fred"] used to indicate the item associated to the string "fred" in the associative array A Java does not use array notation for maps, but the idea is that same: A map is like an array, but the indices for a map are arbitrary objects, not integers. In a map, an object that serves as an "index" is called a key The object that is associated with a key is called a value A key can have at most one associated value, but the same value can be associated to several different keys
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-369
Maps
SLIDE-370
SLIDE-371
public class HashMap_Example { String[] names = {"Jamie", "SuzyQ", "Shannon", "Daisy", "Manny", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Tommy", "Kristy"}; String[] countries = {"USA", "China", "Mexico", "USA", "China", "France", "USA", "China", "Mexico", "China", "USA", "Mexico", "China", "USA", "USA", "USA", "Usa", "China", "USA", "China"};
SLIDE-372
Set set = hashmap.keySet(); Iterator iterator = set.iterator(); while (iterator.hasNext()) { Object key = iterator.next(); Object value = hashmap.get(key); System.out.println(key + " maps to " + value); }
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-373
SLIDE-374
SLIDE-375
Set entrySet()
SortedMap headMap(Object toKey) Returns a view of the portion of this map whose keys are strictly less than toKey. Set keySet() Object Object void Object int size() lastKey() putAll(Map map) remove(Object key) Returns a Set view of the keys contained in this map. Returns the last (highest) key currently in this sorted map. Copies all of the mappings from the specified map to this map. Removes the mapping for this key from this TreeMap if present. Returns the number of key-value mappings in this map.
put(Object key, Object value) Associates the specified value with the specified key in this map.
SortedMap subMap(Object fromKey, Object toKey) Returns a view of the map whose keys range from fromKey, inclusive, to toKey, exclusive. SortedMap tailMap(Object fromKey) Returns a view of the map whose keys are greater than or equal to fromKey. Collection values() Returns a collection view of the values contained in this map.
SLIDE-376
public class TreeMap_Example { String[] names = {"Jamie", "SuzyQ", "Shannon", "Daisy", "Manny", "Sally", "Callie", "Celest", "Malcholm", "Eric", "George", "Sharon", "Carolyn", "Jim", "Danny", "Roger", "Will", "Gina", "Tommy", "Kristy"}; String[] countries = {"USA", "China", "Mexico", "USA", "China", "France", "USA", "China", "Mexico", "China", "USA", "Mexico", "China", "USA", "USA", "USA", "Usa", "China", "USA", "China"};
SLIDE-377
SLIDE-379
SLIDE-380
Descendants to the left have smaller data values than the node data value Descendants to the right have larger data values than the node data value
SLIDE-381
SLIDE-382
Summary Hash Maps Tree Maps Hash Sets Tree Sets Hash Codes
SLIDE-383
5.
To use inheritance to customize panels and frames To understand Java's user interface components are added to a container To understand the use of layout managers to arrange user interface components in a container To become familiar with common user interface components such as buttons, text components, combo boxes, and menus To build programs that handle events from user interface components
SWING Books
Pure JCF Swing. Sams. Dr. Satyaraj Pantham. (1999) The JFC Swing Tutorial. Sun Press. Kathy Walrath. (1999). Core Swing, Advanced Programming. Prentice Hall. Kim Topley. (2000). Java 2 Black Book (2001). Steven Holzner. Java Look and Feel Design Guide. (2001). http://java.sun.com/products/jlf/ed2/book/
Background for this section Pages 336 358 in java software solutions 4th ed or Pages 473-518 in the Big Java 1st ed.
SLIDE-385
SLIDE-386
SWING Components
JApplet JButton JCkeckBox JColorChooser JComboBox JDesktopPane JDialog JFileChooser JPopupMenu JProgressBar JRadioButton JFrame JLabel JList JMenu JMenuBar JMenuItem JOptionPane JPanel JPasswordField JScrollBar JSlider JTable JTextArea JTextPane JTabbedPane JSplitPane JToggleButton JToolBar JToolTip JTree
SLIDE-387
SWING Example
SLIDE-388
SWING Example
SLIDE-389
SWING Example
SLIDE-390
SWING Example
The following example illustrates 1. Checkboxes, radio buttons 2. Fonts, bold, italics 3. Borders 4. Frames and Panels 5. Combo boxes 6. Frame titles 7. GridLayout and containers 8. Event notification 9. General Code Format
SLIDE-391
SWING Example (2 of 8)
/** * Main Class for Swing Tester for CSC200 and CIS263 * @author Jim Adams */ public class Tester01 extends JFrame { private JLabel sampleField; private JCheckBox italicCheckBox; private JCheckBox boldCheckBox; private JRadioButton smallButton; private JRadioButton mediumButton; private JRadioButton largeButton; private JComboBox facenameCombo; private int private int x_loc y_loc = 0; = 0;
/** * Default Constructor * @author Jim Adams * @param None * @return Nothing */ public Tester01() { x_loc = 100; y_loc = 100; }
SLIDE-392
SWING Example (3 of 8)
/** * Main Entry Point for Public * Displays the main panel * @author Jim Adams * @param None * @return Nothing */ public void displayMainPanel() { JFrame frame = new JFrame("This is Jim's Swing Tester"); JPanel controlPanel = new JPanel(); // main panel JPanel facenamePanel = createComboBox(); // combobox panel JPanel sizeGroupPanel = createCheckBoxes(); // check box panel JPanel styleGroupPanel = createRadioButtons(); // radio button panel sampleField setSampleFont(); = new JLabel("Jim's Swing Test"); // rows, cols
controlPanel.setLayout(new GridLayout(4, 1)); controlPanel.add(sampleField); controlPanel.add(facenamePanel); controlPanel.add(sizeGroupPanel); controlPanel.add(styleGroupPanel); frame.getContentPane().add(controlPanel); frame.setSize(300, 300); frame.setLocation(x_loc, y_loc); frame.setVisible(true); frame.pack(); }
SLIDE-393
SWING Example (4 of 8)
/** * Add combo box to panel * @author Jim Adams * @param None * @return JPanel */ private JPanel createComboBox() { JPanel panel = new JPanel(); facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); facenameCombo.addItem("Monospaced"); facenameCombo.setEditable(true); facenameCombo.addActionListener(new ChoiceListener()); panel.add(facenameCombo); return panel; }
Code tested 05/30/2005
SLIDE-394
SWING Example (5 of 8)
/** * Add check boxes buttons to panel * @author Jim Adams * @param None * @return JPanel */ private JPanel createCheckBoxes() { JPanel panel = new JPanel(); italicCheckBox = new JCheckBox("Italic"); italicCheckBox.addActionListener(new ChoiceListener()); boldCheckBox = new JCheckBox("Bold"); boldCheckBox.addActionListener(new ChoiceListener()); panel.add(italicCheckBox); panel.add(boldCheckBox); panel.setBorder(new TitledBorder(new EtchedBorder(), "Style")); return panel; }
SLIDE-395
SWING Example (6 of 8)
/** * Add radio buttons to panel * @param None * @return JPanel */ private JPanel createRadioButtons() { JPanel panel = new JPanel(); smallButton = new JRadioButton("Small"); smallButton.addActionListener(new ChoiceListener()); mediumButton = new JRadioButton("Medium"); mediumButton.addActionListener(new ChoiceListener()); largeButton = new JRadioButton("Large"); largeButton.addActionListener(new ChoiceListener()); largeButton.setSelected(true); ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton);
Code tested 05/30/2005 panel.add(smallButton); panel.add(mediumButton); panel.add(largeButton); panel.setBorder(new TitledBorder(new EtchedBorder(), "Size"));
return panel;
SLIDE-396
SWING Example (7 of 8)
/** * Set Fonts, Sizes, etc * @author Jim Adams * @param None * @return Nothing */ private void setSampleFont() { String facename = (String) facenameCombo.getSelectedItem(); int style = 0; if (italicCheckBox.isSelected()) style = style + Font.ITALIC; if (boldCheckBox.isSelected()) style = style + Font.BOLD; int size = 0; final int SMALL_SIZE = 24; final int MEDIUM_SIZE = 36; final int LARGE_SIZE = 48; if (smallButton.isSelected()) size = SMALL_SIZE; else if (mediumButton.isSelected()) size = MEDIUM_SIZE; else if (largeButton.isSelected()) size = LARGE_SIZE; sampleField.setFont(new Font(facename, style, size)); sampleField.repaint(); }
SLIDE-397
SWING Example (8 of 8)
/** * Inner Class for Action Listener * @author Jim Adams * @param None * @return Nothing */ class ChoiceListener implements ActionListener { public void actionPerformed(ActionEvent event) { setSampleFont(); } } // end of inner class
SLIDE-398
SWING Example
What else could we have done with this class?
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.
Different borders Icon on top title bar Added Images Background colors Foreground colors Locked the physical size and location Watched the mouse Add tool bars Add tool tips Add menus Add other components, buttons, sliders, etc Set a different look and feel (Windows, Mac, etc) Used different layout managers .
SLIDE-399
SLIDE-400
SLIDE-401
SLIDE-402
Unlike secondary windows, which should close automatically when their associated windows are closed, utility windows should remain open when primary windows are closed. User choices made in a utility window refer to and affect the active primary window. A utility window remains on screen for an extended period of time while users go back and forth between the utility window and primary windows. In contrast, a secondary window is designed to enable users to resolve an issue in an associated primary window and is usually dismissed once users have resolved the issue.
SLIDE-404
Organizing Window Contents Panels Scroll Panes Tabbed Panes Split Panes
SLIDE-405
SLIDE-406
SLIDE-407
Both horizontal and vertical scroll boxes have a minimum size of 16 x 16 pixels so that users can still manipulate them when viewing very long documents or lists. At either end of the scrollbar is a scroll arrow, which is used for controlling small movements of the data.
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-408
SLIDE-409
SLIDE-410
SLIDE-411
SLIDE-412
Layout Management
A Container arranges its components By default, JPanel places components from left to right, then starts a new row if needed Panel layout is carried out by the FlowLayout manager You can set other layout managers if you wish
1. 2. 3. 4.
SLIDE-413
Jims Hint:
Layout Management
1. Create JFrame Object 2. Create JPanels Objects 3. Create Border Layouts Objects 4. Create Components 5. Add Components to JPanels 6. Add JPanels to JFrames 7. Show the JFrame frame.setVisible(true);
Excellent online book by Sun Microsystems http://java.sun.com/products/jlf/ed2/book/
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-414
Various Layout Managers BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout SpringLayout
Layout Management
SLIDE-415
Layout Management
SLIDE-416
Border Layout
Border Layout places components into geographical-based positions like center, north, west, south, east
panel.add(textField, BorderLayout.SOUTH);
frame.getContentPane().add(textField,BorderLayout.SOUTH);
Border layout grows components to fit an area To avoid growth, place component into panel (with flow layout), then add panel to content pane
SLIDE-417
Card Layout
The CardLayout class lets you implement an area that contains different components at different times A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel the CardLayout displays An alternative to using CardLayout is using a tabbed pane, which provides similar functionality but with a pre-defined GUI
SLIDE-418
Spring Layout
SpringLayout is a flexible layout manager It lets you specify precise relationships between the edges of components under its control. For example, you might define that the left edge of one component is a certain distance (which can be dynamically calculated) from the right edge of a second component
SLIDE-419
Grid Layout
Lays out components in rows and columns All components have the same size
Add components left to right Top row first, then second row, etc.
panel.setLayout(new GridLayout(4, 3)); panel.add(button7); panel.add(button8); panel.add(button9); panel.add(button4); panel.add(button5); panel.add(button6); panel.add(button1); panel.add(button2); panel.add(button3);
// y, x
SLIDE-420
// border inset
SLIDE-421
Container container = null; container = this.getContentPane(); GridBagLayout grid = new GridBagLayout(); container.setLayout(grid); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.insets = new Insets(5,5,5,5); // border inset c.gridx = 1; c.gridy = 1; c.gridwidth = 1; c.gridheight = 1; c.weightx=1.0; c.weighty=1.0; JButton button = new JButton(Button1); grid.setConstraints(button, c); container.add(button);
SLIDE-422
//
SLIDE-424
SLIDE-426
Box Layout
The BoxLayout class puts components in a single row or column. It respects the components' requested maximum sizes and also lets you align components.
SLIDE-427
Box Layout
Rigid Area
Use this when you want a fixed-size space between two components. For example, to put 5 pixels between two components in a left-to-right box, you can use this code:
http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html
SLIDE-428
Box Layout
Glue
Use this to specify where excess space in a layout should go. Think of it as semiwet glue stretchy and expandable, yet taking up no space unless you pull apart the components that it's sticking to. For example, by putting horizontal glue between two components in a left-to-right box, you make any extra space go between those components, instead of to the right of all the components. Here's an example of making the space in a left-to-right box go between two components, instead of to the right of the components:
SLIDE-429
SLIDE-430
Radio Buttons
Radio buttons are mutually exclusive Button group turns one button off when the next one is turned on sButton = new JRadioButton("Small"); mButton = new JRadioButton("Medium"); lButton = new JRadioButton("Large"); ButtonGroup group = new ButtonGroup(); group.add(sbutton); group.add(mbutton); group.add(lbutton); Buttons in a group are tested together for mutuality Button group doesn't place buttons into panel--need to add them: panel.add(sButton); Inside your action listener, test if selected if (sButton.isSelected()) . . .
SLIDE-431
Radio Buttons
Radio Button Constructors
public JRadioButton(); public JRadioButton(Icon icon); public JRadioButton(Icon icon, boolean selected); public JRadioButton(String text); public JRadioButton(String text, boolean selected); public JRadioButton(String text, Icon icon, boolean selected);
SLIDE-432
radio1.addActionListener(new ButtonListener1()); radio2.addActionListener(new ButtonListener2()); private class ButtonListener1 implements ActionListener { public void actionPerformed(ActionEvent e) { Java Code for Radio Button 1 } } private class ButtonListener2 implements ActionListener { public void actionPerformed(ActionEvent e) { Java Code for Radio Button 2 } Handling each }
private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String button = e.getActionCommand(); if (button.equals("Next")) { do something } Handling many buttons } with one listener }
SLIDE-434
Check Boxes
Similar to radio button, but not mutually exclusive
JCheckBox b1 = new JCheckBox("Match Case"); JCheckBox b2 = new JCheckBox("Whole Word");
SLIDE-435
Check Boxes
Whenever a check box is selected or deselected an event of type ItemEvent is fired Methods from the ItemEvent class
public Object getItem(); // retrieves the item label public ItemSelectable getItemSelectable() public int getStateChanged()
SLIDE-436
Combo Boxes
Use less space than radio buttons Users can type other values Combo between list selection and text field JComboBox faceName = new JComboBox(); faceName.addItem("Serif"); faceName.addItem("SansSerif"); faceName.addItem("Monospaced"); Get user selection sel = (String)faceName.getSelectedItem();
SLIDE-437
Java Menus
Jims Hint: 1. Declare the Menu Bars, Menus and Menu Items 2. Add menu items to the menus 3. Add menus to the menu bar 4. Add menu bar to the JFrame 5. Add action Listeners to the menu Items 6. Add Hot Keys to menu items
SLIDE-438
Menu Items
Add menu bar to frame JMenuBar bar = new JMenuBar(); frame.setJMenuBar(bar); Add menus to the menu bar JMenu fileMenu = new JMenu("File"); bar.add(fileMenu); Add menu items to the menu JMenuItem fileNew = new JMenuItem("New"); JMenuItem fileOpen = new JMenuItem(Open"); fileMenu.add(fileNew); fileMenu.add(fileOpen); Add action listener to the menu item fileNew.addActionListener(new fileNewListener()); fileOpen.addActionListener(new fileOpenListener())
SLIDE-439
Menu Components
JMenuBar JMenu JMenu JMenu JMenu JMenu JMenu JMenuItem JMenuItem JMenuItem JMenuItem JMenuItem JMenuItem JMenuItem JMenuItem MainMenu FileMenu EditMenu ViewMenu BuildMenu ToolsMenu HelpMenu MI_New MI_Close MI_Open MI_Save MI_SaveAs MI_Print MI_Exit MI_Cut = new JMenuBar(); = = = = = = new new new new new new = = = = = = = = JMenu("File"); JMenu("Edit"); JMenu("View"); JMenu("Build"); JMenu("Tools"); JMenu("Help"); new new new new new new new new JMenuItem("New"); JMenuItem("Close"); JMenuItem("Open"); JMenuItem("Save"); JMenuItem("Save As"); JMenuItem("Print"); JMenuItem("Exit"); JMenuItem("Cut");
SLIDE-440
Menu Items
FileMenu.add(MI_New); FileMenu.add(MI_Open); FileMenu.add(MI_Save); FileMenu.add(MI_SaveAs); FileMenu.add(new JSeparator()); FileMenu.add(MI_PrinterSetup); FileMenu.add(MI_Exit); EditMenu.add(MI_Cut); EditMenu.add(MI_Copy); EditMenu.add(MI_Find); EditMenu.add(MI_Replace); EditMenu.add(MI_Paste); ViewMenu.add(MI_CrossReference); ViewMenu.add(MI_FreqTable); ViewMenu.add(MI_SymbolTable); ViewMenu.add(MI_AssembledCode); BuildMenu.add(MI_Assemble); BuildMenu.add(MI_MakeEXE); BuildMenu.add(MI_MakeCOM);
SLIDE-441
SLIDE-442
SLIDE-443
Constructing a Slider
Constructors JSlider js = new JSlider(); Has range (0,100) with initial value of 50 JSlider(int min, int max, int value); Can specify range and initial value JSlider(int orientation, int min, int max, int value); Can use JSlider.HORIZONTAL and JSlider.VERTICAL
SLIDE-444
Constructing a Slider
Can set minimum, maximum, paint the tick marks, major spacing and minor spacing of ticks.
slider.setMajorTickSpacing(int); slider.setMinorTickSpacing(int);
SLIDE-445
Listening to a Slider
Look for addxxxListener:
void addChangeListener(ChangeListener listen)
Listening to a Slider (1 of 2)
import javax.swing.*; import javax.swing.event.*; import java.awt.*; public class Slider_Demo extends JFrame { JSlider slider = new JSlider(JSlider.HORIZONTAL,0,500,250); JLabel label = new JLabel("250",JLabel.CENTER); Font font = new Font("Verdana",Font.BOLD, 14); public Slider_Demo() { // set up the JFrame, baby JFrame frame = new JFrame(); frame.setTitle("Slider Test"); frame.setSize(350,160); // x,y frame.setVisible(true); frame.setLocation(250, 200); frame.setBackground(new Color(207,207,207)); slider.addChangeListener(new SliderListener()); slider.setPaintTicks(true); slider.setMajorTickSpacing(100); slider.setMinorTickSpacing(50); slider.setLabelTable(slider.createStandardLabels(50)); slider.setPaintLabels(true);
December 30, 2006 Copyright 2004-2007, Jim Adams
SLIDE-447
Listening to a Slider (2 of 2)
BorderLayout maingrid = new BorderLayout(2,2); JPanel panel = new JPanel(); panel.setLayout(maingrid); // border layout panel.add(slider, BorderLayout.CENTER); panel.add(label, BorderLayout.NORTH); frame.getContentPane().add(panel); frame.show(); } class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent chngEvt) { String value=""; int slidervalue=0; JSlider sliderTemp = (JSlider) chngEvt.getSource(); label.setFont(font); slidervalue=sliderTemp.getValue(); value=Integer.toString(slidervalue); label.setText(value); } // end of listener } // end of inner class // end of outer class
Code Tested 08/25/2004
SLIDE-448
SLIDE-450
File Chooser
SLIDE-451
File Chooser
Code tested 08/25/2004
public class Chooser { public static void main(String[] args) { int selected=0; File file = null; JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.setDialogTitle("Select Destination Directory"); chooser.setApproveButtonText("Select This File"); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File selectedfile = chooser.getSelectedFile(); System.out.println(selectedfile); } if (chooser.showOpenDialog(null) == JFileChooser.CANCEL_OPTION) { System.out.println("Cancel Button Detected"); } // end of main // end of class
} }
SLIDE-452
File Chooser
static static static static static java.lang.String APPROVE_LABEL int APPROVE_OPTION java.lang.String CANCEL_LABEL int CANCEL_OPTION int ERROR_OPTION
Returns Returns Returns Get the the currently displayed directory. the currently selected file filter. the current file-selection mode. File selected by the user.
SLIDE-453
Color Chooser
Constructors
public JColorChooser() public JColorChooser(Color initial color);
SLIDE-454
public class ColorChooser extends JFrame { public void Choose() { Color color = JColorChooser.showDialog(ColorChooser.this, "Select a new color...", Color.white); } } public class ColorChooserTester { public ColorChooserTester() { } public static void main(String[] args) { ColorChooser cc = new ColorChooser(); cc.Choose(); }
Code tested 08/25/2004
SLIDE-455
SLIDE-456
SLIDE-458
Jims Hint:
Declare the component such as a button, combo box, etc Set the component attributes Set the property addActionListener to point to an inner class Add the inner class with an actionPerformed method Call a method from the inner class method
December 30, 2006 Copyright 2004-2007, Jim Adams SLIDE-459
SLIDE-460
SLIDE-461
SLIDE-462
Summary
1. Understand how GUI components are added to a container 2. Layout managers 3. Common user interface components, buttons, combo boxes, radio dials and menus 4. Handle events from user components
SLIDE-463