CS#180#Problem#Solving#and#ObjectOriented# …# name:# “Mango”# color:Yellow price:3.99#...
Transcript of CS#180#Problem#Solving#and#ObjectOriented# …# name:# “Mango”# color:Yellow price:3.99#...
CS 180 Problem Solving and Object Oriented Programming Fall 2011
Notes for Week 12: Nov 7-‐11, 2011
Aditya Mathur Department of Computer Science Purdue University West LafayeLe, IN, USA
hLp://www.cs.purdue.edu/homes/apm/courses/CS180Fall2011/
This Week:
11/7-‐11 1. Quiz 2. Review 3. Concurrent programming 4. Concurrent linear search 5. CHALLENGE PROBLEM 6. Concurrent bubble sort and
merge
Readings and Exercises for Week 12 [Prepara_on for Exam 2]
Readings: Chapters: 2, 3, 4, 5, 7, 8, 1, and 19 No ques_ons on: Interfaces, inheritance, JOp_onPane, images, sounds, applets
Focus
Exercises:
Exam 2 Prac_ce Problem Set [available via the course web site] ©Aditya Mathur. CS 180. Fall 2011. Week 12
File input (Scanner)/output (PrintWriter); Arrays: single and mul_dimensional; GUIs (with Ac_on and Mouse Listeners; Grid and Border layouts).
Exam 2
When: Wednesday November 9, 2011; 8-‐10pm.
Where: WTHR 200
Format: Open book [Any one book on Java]
Two programming problems.
Problem 1: Arrays/Files
Problem 2: GUIs
©Aditya Mathur. CS 180. Fall 2011. Week 12
BRING YOUR ID!
Project 4
To type password so that characters do not show, use, but
only if you wish to,
JPasswordField pass=new JPasswordField ()
instead of JTextField().
©Aditya Mathur. CS 180. Fall 2011. Week 12
1. Names of formal and actual parameters must be the same
A True
B. False
©Aditya Mathur. CS 180. Fall 2011. Week 12
2. Types of formal and actual parameters must be the same or conver_ble.
A True
B. False
©Aditya Mathur. CS 180. Fall 2011. Week 12
3. One of the following is incorrect. Which one.?
A. JPanel p=new JPanel();
B. JFrame f= new JFrame(“Is this OK?”);
C. JPanel p= new JPanel(new GridLayout(3, 4)); D. JFrame f= new JFrame(new GridLayout(3, 4);
©Aditya Mathur. CS 180. Fall 2011. Week 12
4. One of the following is incorrect. Which one?
A. int [][] a=new int[][4]; B. int [][] a=new int[100][4]; C. int [][] a=new int[3][4]; D. int [][] a=new int[100][0];
©Aditya Mathur. CS 180. Fall 2011. Week 12
5. Default layout for a JPanel is
A. GridLayout B. FlowLayout C. BorderLayout D. BoxLayout
©Aditya Mathur. CS 180. Fall 2011. Week 12
6. When transferring actual parameters to a method the following is passed
A. Value of the actual parameter
B. Reference to the actual parameter
C. None of the above
©Aditya Mathur. CS 180. Fall 2011. Week 12
8. There can be more than one constructor in a class defini_on.
A. True B. False
©Aditya Mathur. CS 180. Fall 2011. Week 12
9. A non-‐sta_c method in a class can directly call a sta_c method in that class.
A. True B. False
©Aditya Mathur. CS 180. Fall 2011. Week 12
10. A sta_c method in a class can directly call a non-‐sta_c method in that class.
A. True B. False
©Aditya Mathur. CS 180. Fall 2011. Week 12
File object
• File f; // declares an object of type File
• File f=new File (“data.txt”); // Create a File object
• String filename=“data.txt”;
File f=new File (fileName); // Create a File object
• Full pathnames can be specified when crea_ng a File
object.
©Aditya Mathur. CS 180. Fall 2011. Week 12
File Input
• File f=new File (“data.txt”); // Create a File object
Scanner inFile=new Scanner(f); // Creates a Scanner for data.txt
• Must be inside try-‐catch.
• boolean b= inFile.hasNext();// Checks if there is more data to be input
String s=inFile.next(); // Read a string
• int num=inFile.nextInt(); // Read an int
• double num=inFile.nextDouble(); // Read a double
©Aditya Mathur. CS 180. Fall 2011. Week 12
File Output
• File f=new File (“data.txt”); // Create a File object
PrintWriter outFile=new PrintWriter(f); // Creates a writer for data.txt
• Must be inside try-‐catch.
• outFile.print(d); // Write d in to the file; d may be any primi_ve type,
// string, or even an arbitrary object.
• outFile.println(d); // Same as print() but terminates line.
• outFile.prinq(format, d); // Same as print but formaLed
• outFile.close();// Needed to ensure all data is flushed to the file.
©Aditya Mathur. CS 180. Fall 2011. Week 12
Arrays of primi_ve types
• int [] a; // Declare an array
• int [] a=new int [n]; // Create an array
• long [][] x; // Declare an array
• long [][] x=new long [10][]; // Create an array
• long [][]x=new long [10][5]; // Create an array
©Aditya Mathur. CS 180. Fall 2011. Week 12
Array of primi_ve types: Visual int [] a=new int [3]; // Create an array
©Aditya Mathur. CS 180. Fall 2011. Week 12
0
1
2
0
0
0
a
a[0]=5; 0
1
2
5
0
0
a
Arrays of objects • JBuLon [] b; • JBuLon [] b=new JBuLon[n];
©Aditya Mathur. CS 180. Fall 2011. Week 12
Array of objects: Visual JBuLon [] b=new JBuLon[3];
©Aditya Mathur. CS 180. Fall 2011. Week 12
0
1
2
null
null
null
b
Array of objects: Null pointer excep_on JBuLon [] b=new JBuLon[3];
©Aditya Mathur. CS 180. Fall 2011. Week 12
0
1
2
null
null
null
b
buLon[0].setText("Hello");
What happens if we do the following?
Array of objects: Crea_ng an object JBuLon [] b=new JBuLon[3] b[0]=new JBuLon(“Hello”);
©Aditya Mathur. CS 180. Fall 2011. Week 12
0
1
2
null
null
b Hello
Array of objects: Modifying an object JBuLon [] b=new JBuLon[3] b[0]=new JBuLon(“Hello”);
©Aditya Mathur. CS 180. Fall 2011. Week 12
b[0].setText(”Hi!");
What happens if we do the following?
0
1
2
null
null
b Hi!
Array of objects: Another example
Fruit [] f=new Fruit[3]
©Aditya Mathur. CS 180. Fall 2011. Week 12
f[0].setFruitColor(Color.Yellow); f[0].setPrice(3.99);
0
1
2
null
null
f null
f[0]=new Fruit(“Mango”); 0
1
2
null
null
f
name: “Mango” color: price:
name: “Mango” color: Yellow price:3.99
Method header
©Aditya Mathur. CS 180. Fall 2011. Week 12
Modifier public/ private/ none
Modifier sta_c/ none
Return type
Name Parameters 0 or more
public boolean find(int [] a, int x)
Method parameters
©Aditya Mathur. CS 180. Fall 2011. Week 12
public boolean find(int [] a, int x)
Value parameter
Reference parameter
Value parameter: primi_ve types
Reference parameter: objects
Value parameters
©Aditya Mathur. CS 180. Fall 2011. Week 12
public boolean find(int [] a, int x){
System.out.println(x); x++;
}
int y=15; int[] num={2, 3, 15, -‐29}; boolean found=find(num, y) System.out.println(found + ” “+ y);
What is displayed?
Value of actual parameter is passed
Reference parameters
©Aditya Mathur. CS 180. Fall 2011. Week 12
public boolean find(int [] a, int x){ System.out.println(a[1]); x++; a[1]++;
}
int y=15; int [] num={2, 3, 15, -‐29}; boolean found=find(num, y) System.out.println(found + ” “+ num[1]);
What is displayed?
Reference to actual parameter is passed
The main() method
©Aditya Mathur. CS 180. Fall 2011. Week 12
public sta_c void main(String [] args){
}
Is this value or a reference parameter?
How can we pass parameters to the main() method?
Method parameter: summary
©Aditya Mathur. CS 180. Fall 2011. Week 12
• A method may have zero or more parameters.
• Each parameter has a name.
• Each parameter must have a type
• All parameters are passed by value. For primi_ve types the value of the actual parameter is passed. For reference types a reference to the object is passed.
• Each method must have a return type.
• Each parameter becomes a local variable for the method.
• A constructor is a special method that has no return type.
Class and instance variables
©Aditya Mathur. CS 180. Fall 2011. Week 12
public class Home{ public sta_c String measureUnit=“Square Feet”; public sta_c String code=“Pub. L. 110-‐140”; private String address=“”; private int bedRooms=4; public Home(String a, int r){
address=a; bedRooms=r; }
public int getBedrooms(){ return(bedRooms);
}
Class variables
Instance variables
Class and instance variables
©Aditya Mathur. CS 180. Fall 2011. Week 12
Home h1=new Home(“1400 X Street”, 4); address=“1400 X Street” bedRooms=4
Home h2=new Home(“1500 Y Street”, 3);
address=“1500 Y Street” bedRooms=3
System.out.println(Home.getBedRooms());
System.out.println(h2.getBedRooms());
System.out.println(h1.code);
System.out.println(h2.code);
System.out.println(h1.getBedRooms());
h1
h2
System.out.println(Home.code);
Class variables
©Aditya Mathur. CS 180. Fall 2011. Week 12
Declared using the sta_c keyword.
Not a part of the object, but part of the class in which they are declared.
Accessible via the objects created from that class
Declare a variable or a method as sta_c only if does not depend on the object.
Instance variables
©Aditya Mathur. CS 180. Fall 2011. Week 12
Declared without using the sta_c keyword
Part of an object
Accessible via the objects created from the parent class
Declare a variable as an instance variable if its value depends on the object.
The main() method
©Aditya Mathur. CS 180. Fall 2011. Week 12
Is declared to be sta_c
Can it access instance variables in its parent class?
What variables and methods in the parent class can the main method access?
Accessibility rules
©Aditya Mathur. CS 180. Fall 2011. Week 12
Modifier Class Package Subclass World
public Y Y Y Y
private Y N N N
none Y Y N N
If a variable or an object declara_on uses this modifier
then can this variable or object be used inside ?
Package: A collec_on of classes iden_fied as a Java package. World: Collec_on of packages
Y: Yes. N: No.
Local variables
©Aditya Mathur. CS 180. Fall 2011. Week 12
public void test(int x){ int p, q; }
x, p, q are local to method test. test is public and hence global and can be used in all classes. Variables and objects declared inside a method are local to that method.
Local variables: Use of public and private modifiers
©Aditya Mathur. CS 180. Fall 2011. Week 12
public void test(int x){ int p, q; public int z; }
x, p, q are local to method test. test is public and hence global and can be used in all classes. Declara_ons inside a method cannot be preceded by public or private.
Global variables
©Aditya Mathur. CS 180. Fall 2011. Week 12
public class Toy{ public String name; private String owner; }
name is global as it is declared to be public. Owner is local to this class Toy is global and can be used anywhere.
Local and global variables: Example public class X{ public JBuLon plus; public void doSomething(String c){
int z; for (int i=0; i<10; i++){ int p;
} System.out.println(i, p); } // end of method
}// end of class
©Aditya Mathur. CS 180. Fall 2011. Week 12
z, c can be use here
i can be Used here
i, p out of scope
plus can be used here
Inheritance
©Aditya Mathur. CS 180. Fall 2011. Week 12
public class Fruit{ public String name; private String color=“Red”; int type; public void changeColor
(String c){ Color=c;
} public String getColor(){
return color; } }
public class Mango extends Fruit{ public String origin; public void harvest(){
} public String getOrigin(){
return color; } }
All methods and local variables/objects are available to Mango.
Inheritance: Another example
©Aditya Mathur. CS 180. Fall 2011. Week 12
public class Gui extends JFrame{ }
All methods and local variables/objects of JFrame are available to Gui.
GUI: Widget/Methods
©Aditya Mathur. CS 180. Fall 2011. Week 12
JFrame JPanel JBuLon JTextField JMenuBar JMenu JMenuItem
setSize() setVisible( ) setText() getText add()
GUI: Listeners/Methods
©Aditya Mathur. CS 180. Fall 2011. Week 12
Ac_onListener MenuListener KeyListener MouseListener
getSource() addAc_onListener()
GUI: Interface
©Aditya Mathur. CS 180. Fall 2011. Week 12
A class implements an interface All methods in the interface must be implemented. Ac_onListener is an interface.
GUI: Abstract Class
©Aditya Mathur. CS 180. Fall 2011. Week 12
Similar to interface but may implement some methods thus avoiding the need to implement all methods. MouseAdapter is an abstract class.
Announcements
©Aditya Mathur. CS 180. Fall 2011. Week 11
• No Feast With Faculty tonight due to Exam 2.
• Project 5 will be assigned this Friday, earlier than adver_sed, but the due date will not change.
• I will be out of the country next week.
• On Nov 14/16 Suleyman Cen_nas will solve problems related to concurrent programming. Please aLend!
• Exam 2 TODAY! WTHR 200. 8pm.
Dividing work into small segments
©Aditya Mathur. CS 180. Fall 2011. Week 11
class
Instance variables Class variables Methods
class
Instance variables Class variables Methods
class
Instance variables Class variables Methods
Program
Concurrency
©Aditya Mathur. CS 180. Fall 2011. Week 11
T
T1 T2 TN . . . .
T
Main thread controls the distribu_on of work
N threads execu_ng concurrently to execute N tasks T1, T2…TN.
Distribute work
Task T is divided into N simpler tasks and executed in parallel
Threads
©Aditya Mathur. CS 180. Fall 2011. Week 11
• Thread is a class
• A thread is a sequence of computa_ons that can run in parallel with other threads.
• One uses the Thread class to create a thread.
Problem
©Aditya Mathur. CS 180. Fall 2011. Week 11
• Given doubles x and y and a boolean z, write a program to compute the following
sin(x)/cos(y)+(x2+y2); if z is true sin(x)/cos(y)+(x2 -‐ y2); if z is false
Problem: Solu_on architecture
©Aditya Mathur. CS 180. Fall 2011. Week 11
T
T1 T2
T
T: Perform the given task
T1: Compute a part of the expression
T2: Compute a other part of the expression
Combine the results of T1 and T2
How many threads?
Problem: Algorithm
©Aditya Mathur. CS 180. Fall 2011. Week 11
Thread A: Input: x and y
Compute sin(x)/cos(y)
Thread B: Input: x, y, z
Compute x2+y2 if z is true or x2-‐y2 if z is false
Thread C (control thread): • Input: x , y, z; • Create an object e1(Thread A ); • Create can object e2(Thread B); • Start e1; • Start e2; • Wait for e1 and e2 to complete; • Get value computed by e1; • Get value computed by e2; • Add the two values and display the
result;
Thread: What is it?
©Aditya Mathur. CS 180. Fall 2011. Week 12
• A thread is a sequence of computa_on that can run in
parallel with other threads.
• Every program has at least one thread of computa_on.
• Each thread is associated with an instance of the class
Thread.
• A program with two or more threads is generally referred to
as a mul_threaded program.
• A mul_threaded program is generally used to speed up the
solu_on to a problem.
Thread: Typical lifecycle
©Aditya Mathur. CS 180. Fall 2011. Week 12
Define class that extends Thread.
Create thread.
Start thread.
Wait for thread to terminate.
Get results from thread.
Use results from thread.
Thread: Defining a class
©Aditya Mathur. CS 180. Fall 2011. Week 12
Thread is a class. One way to create a new thread is to first
define a class that extends the Thread class.
public class Search extends Thread{
String [] x; // For use by a thread
String s; // Another object for use by the thread
int tID; // Thread ID if needed
int start, end; // Start and end indices for search
boolean found; // Computed by the thread
}
Thread: The constructor
©Aditya Mathur. CS 180. Fall 2011. Week 12
A class that extends Thread generally has a constructor that is
used to pass parameters to a thread as follows.
public Search (String [] a, String s, int start, int end, int tID, ){
// Save parameters for use when the thread executes
x=a;
this.s=s; this.start=start; this.end=end;
this.tID=tID
}
Thread: The run() method
©Aditya Mathur. CS 180. Fall 2011. Week 12
Unlike the main() method, every thread object created from
Thread must have a run() method.
When a thread is started, its execu_on begins in the run()
method and terminates when the run() method terminates
Thread: The run() method: Example
©Aditya Mathur. CS 180. Fall 2011. Week 12
public void run (){ // Must not have any parameters
// Thread execu_on begins here.
System.out.println(“Hi! I am thread “+tID);
System.out.println(“Bye bye! See you!”);
}
The run() method does not take any parameters. The run() methods does not return any value.
Thread: Other methods
©Aditya Mathur. CS 180. Fall 2011. Week 12
A thread may have methods other than the run() method. Here
is an example.
public boolean getOutcome(){
return (found); // Return the outcome of search }
Methods in a thread may be called during the execu_on of the
run() method and even azer the comple_on of the run()
method.
Thread: run() method
©Aditya Mathur. CS 180. Fall 2011. Week 12
A run() method is like any other method except that it
does not have any parameters or return type.
A run() method may call any other method to complete its
task.
Thread: Crea_on
©Aditya Mathur. CS 180. Fall 2011. Week 12
Create a thread object just as any other object.
The following examples create two thread objects named one
and two.
Search one=new Search (a, s, start, end, 1);
Search two=new Search (a, s, start, end, 2);
Thread: Start of execu_on
©Aditya Mathur. CS 180. Fall 2011. Week 12
Execu_on of a thread must be started using the start() method
for that thread. Here are two examples for star_ng threads
one and two.
one.start(); // Starts the execu_on of thread object one
two.start(); // Starts the execu_on of thread object two
Thread: Wai_ng for comple_on
©Aditya Mathur. CS 180. Fall 2011. Week 12
You may wait for a thread to complete execu_on using the join
() method as follows.
try{
one.join(); // Wait for thread one to complete
two.join(); // Wait for thread one to complete
catch(Excep_on e){}
The try-‐catch block is needed. More on this later!
Thread: Extrac_ng results
©Aditya Mathur. CS 180. Fall 2011. Week 12
You may extract the outcome of a thread’s execu_on in a
variety of way. One way is to use an accessor method to do so.
Here are examples.
boolean f1=one.getOutcome(); // Get search outcome of thread one
boolean f2=two.getOutcome(); // Get search outcome of thread two
Thread: Typical lifecycle [Review]
©Aditya Mathur. CS 180. Fall 2011. Week 12
Define class that extends Thread.
Create thread.
Start thread.
Wait for thread to terminate.
Get results from thread.
Use results from thread.
Problem 1
©Aditya Mathur. CS 180. Fall 2011. Week 12
We are given a rather large array of strings. We wish to
write a program that will determine, and display, whether
or not a given string appears in the array.
Given that the array is large, we are required to write a
concurrent program that uses threads to solve the
problem faster than it would if done sequen_ally.
Understanding the problem
©Aditya Mathur. CS 180. Fall 2011. Week 12
The problem is rather straighqorward!
Search algorithm
©Aditya Mathur. CS 180. Fall 2011. Week 12
There are many search algorithms available. Given no
informa_on about how the array of strings is ordered, we will
use a simple linear search algorithm.
The given string will be compared with the first element of the
array, then the next and so on un_l a match is found or all
elements have been compared.
If a match is found, the algorithm returns true, otherwise it
returns false.
Concurrent search: Create threads
©Aditya Mathur. CS 180. Fall 2011. Week 12
a=
0 1 2 3 4 5
q p
r
u
s
t
Given array
Create thread one Pass a, s and start and end indices to the constructor [start=0, end=2]
Given string to be searched: s
Create thread two Pass a, s and start and end indices to the constructor [start=3, end=5]
Concurrent search: Array par__oned
©Aditya Mathur. CS 180. Fall 2011. Week 12
0 1 2
q p
r
3 4 5 u
s
t
Thread one searches in this part of the array
Thread two searches in this part of the array
Concurrent search: Next steps
©Aditya Mathur. CS 180. Fall 2011. Week 12
• Start the threads;
• Wait for the threads to complete;
• Extract the search outcome of each thread;
• If any one of the threads found the string then the
search was successful otherwise the search failed.
Challenge Problem
©Aditya Mathur. CS 180. Fall 2011. Week 12
You are given an array of integers. The integers in the array vary from 0 (inclusive) to 500 (inclusive). You are also given 3 bins.
Write a concurrent program that distributes the integers in the
array into the 3 bins such that bin 1 gets all integers less than
170, bin 2 gets all integers greater than 170 but less than 240,
and bin 3 gets all integers greater than 240.
Sort the bins in ascending order and display.
Challenge Problem: Example
©Aditya Mathur. CS 180. Fall 2011. Week 12
Given:
array={3, 43, 129, 32, 400, 452, 5}
Final contents of the three bins as displayed:
bin 1={3, 5, 32, 43} bin 2={129} bin 3={400, 452}