Download presentation
Presentation is loading. Please wait.
1
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 Lafayette, IN, USA http://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
2
Readings and Exercises for Week 12 [Preparation for Exam 2] Readings: Chapters: 2, 3, 4, 5, 7, 8, 1, and 19 No questions on: Interfaces, inheritance, JOptionPane, images, sounds, applets Focus Exercises: Exam 2 Practice Problem Set [available via the course web site] ©Aditya Mathur. CS 180. Fall 2011. Week 12 File input (Scanner)/output (PrintWriter); Arrays: single and multidimensional; GUIs (with Action and Mouse Listeners; Grid and Border layouts).
3
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!
4
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
5
Quiz ©Aditya Mathur. CS 180. Fall 2011. Week 12
6
1.Names of formal and actual parameters must be the same A True B. False ©Aditya Mathur. CS 180. Fall 2011. Week 12
7
2. Types of formal and actual parameters must be the same or convertible. A True B. False ©Aditya Mathur. CS 180. Fall 2011. Week 12
8
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
9
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
10
5. Default layout for a JPanel is A.GridLayout B.FlowLayout C.BorderLayout D.BoxLayout ©Aditya Mathur. CS 180. Fall 2011. Week 12
11
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
12
7. A constructor is always required. A.True B.False ©Aditya Mathur. CS 180. Fall 2011. Week 12
13
8. There can be more than one constructor in a class definition. A.True B.False ©Aditya Mathur. CS 180. Fall 2011. Week 12
14
9. A non-static method in a class can directly call a static method in that class. A.True B.False ©Aditya Mathur. CS 180. Fall 2011. Week 12
15
10. A static method in a class can directly call a non-static method in that class. A.True B.False ©Aditya Mathur. CS 180. Fall 2011. Week 12
16
Review: Files ©Aditya Mathur. CS 180. Fall 2011. Week 12
17
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 creating a File object. ©Aditya Mathur. CS 180. Fall 2011. Week 12
18
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
19
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 primitive type, // string, or even an arbitrary object. outFile.println(d); // Same as print() but terminates line. outFile.printf(format, d); // Same as print but formatted outFile.close();// Needed to ensure all data is flushed to the file. ©Aditya Mathur. CS 180. Fall 2011. Week 12
20
Review: Arrays ©Aditya Mathur. CS 180. Fall 2011. Week 12
21
Arrays of primitive 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
22
Array of primitive 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
23
Arrays of objects JButton [] b; JButton [] b=new JButton[n]; ©Aditya Mathur. CS 180. Fall 2011. Week 12
24
Array of objects: Visual JButton [] b=new JButton[3]; ©Aditya Mathur. CS 180. Fall 2011. Week 12 0 1 2 null b
25
Array of objects: Null pointer exception JButton [] b=new JButton[3]; ©Aditya Mathur. CS 180. Fall 2011. Week 12 0 1 2 null b button[0].setText("Hello"); What happens if we do the following?
26
Array of objects: Creating an object JButton [] b=new JButton[3] b[0]=new JButton(“Hello”); ©Aditya Mathur. CS 180. Fall 2011. Week 12 0 1 2 null b Hello
27
Array of objects: Modifying an object JButton [] b=new JButton[3] b[0]=new JButton(“Hello”); ©Aditya Mathur. CS 180. Fall 2011. Week 12 b[0].setText(”Hi!"); What happens if we do the following? 0 1 2 null b Hi!
28
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 f f[0]=new Fruit(“Mango”); 0 1 2 null f name: “Mango” color: price: name: “Mango” color: price: name: “Mango” color: Yellow price:3.99 name: “Mango” color: Yellow price:3.99
29
Review: Methods ©Aditya Mathur. CS 180. Fall 2011. Week 12
30
Method header ©Aditya Mathur. CS 180. Fall 2011. Week 12 Modifier public/ private/ none Modifier static/ none Return type NameParameters 0 or more public boolean find(int [] a, int x)
31
Method parameters ©Aditya Mathur. CS 180. Fall 2011. Week 12 public boolean find(int [] a, int x) Value parameter Reference parameter Value parameter: primitive types Reference parameter: objects
32
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
33
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
34
The main() method ©Aditya Mathur. CS 180. Fall 2011. Week 12 public static void main(String [] args){ } Is this value or a reference parameter? How can we pass parameters to the main() method?
35
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 primitive 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.
36
Review: Class and instance variables ©Aditya Mathur. CS 180. Fall 2011. Week 12
37
Class and instance variables ©Aditya Mathur. CS 180. Fall 2011. Week 12 public class Home{ public static String measureUnit=“Square Feet”; public static 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
38
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);
39
Class variables ©Aditya Mathur. CS 180. Fall 2011. Week 12 Declared using the static 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 static only if does not depend on the object.
40
Instance variables ©Aditya Mathur. CS 180. Fall 2011. Week 12 Declared without using the static 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.
41
The main() method ©Aditya Mathur. CS 180. Fall 2011. Week 12 Is declared to be static Can it access instance variables in its parent class? What variables and methods in the parent class can the main method access?
42
Accessibility rules ©Aditya Mathur. CS 180. Fall 2011. Week 12 ModifierClassPackageSubclassWorld publicYYYY privateYNNN noneYYNN If a variable or an object declaration uses this modifier then can this variable or object be used inside ? Package: A collection of classes identified as a Java package. World: Collection of packages Y: Yes. N: No.
43
Review: Local and global variables ©Aditya Mathur. CS 180. Fall 2011. Week 12
44
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.
45
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. Declarations inside a method cannot be preceded by public or private.
46
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.
47
Local and global variables: Example public class X{ public JButton 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
48
Review: Inheritance ©Aditya Mathur. CS 180. Fall 2011. Week 12
49
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.
50
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.
51
Review: GUI ©Aditya Mathur. CS 180. Fall 2011. Week 12
52
GUI: Widget/Methods ©Aditya Mathur. CS 180. Fall 2011. Week 12 JFrame JPanel JButton JTextField JMenuBar JMenu JMenuItem setSize() setVisible( ) setText() getText add()
53
GUI: Listeners/Methods ©Aditya Mathur. CS 180. Fall 2011. Week 12 ActionListener MenuListener KeyListener MouseListener getSource() addActionListener()
54
GUI: Interface ©Aditya Mathur. CS 180. Fall 2011. Week 12 A class implements an interface All methods in the interface must be implemented. ActionListener is an interface.
55
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.
56
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 advertised, but the due date will not change. I will be out of the country next week. On Nov 14/16 Suleyman Centinas will solve problems related to concurrent programming. Please attend! Exam 2 TODAY! WTHR 200. 8pm.
57
Concurrent Programming ©Aditya Mathur. CS 180. Fall 2011. Week 11
58
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
59
Concurrency ©Aditya Mathur. CS 180. Fall 2011. Week 11 TT1T1 T2T2 TNTN.. T Main thread controls the distribution of work N threads executing concurrently to execute N tasks T 1, T 2 …T N. Distribute work Task T is divided into N simpler tasks and executed in parallel
60
Threads ©Aditya Mathur. CS 180. Fall 2011. Week 11 Thread is a class A thread is a sequence of computations that can run in parallel with other threads. One uses the Thread class to create a thread.
61
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)+(x 2 +y 2 ); if z is true sin(x)/cos(y)+(x 2 - y 2 ); if z is false
62
Problem: Solution architecture ©Aditya Mathur. CS 180. Fall 2011. Week 11 T T1T1 T2T2 T T: Perform the given task T 1 : Compute a part of the expression T 2 : Compute a other part of the expression Combine the results of T 1 and T 2 How many threads?
63
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 x 2 +y 2 if z is true or x 2 -y 2 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;
64
Problem: Program ©Aditya Mathur. CS 180. Fall 2011. Week 11
65
Back to Concurrency ©Aditya Mathur. CS 180. Fall 2011. Week 12
66
Thread: What is it? ©Aditya Mathur. CS 180. Fall 2011. Week 12 A thread is a sequence of computation that can run in parallel with other threads. Every program has at least one thread of computation. Each thread is associated with an instance of the class Thread. A program with two or more threads is generally referred to as a multithreaded program. A multithreaded program is generally used to speed up the solution to a problem.
67
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.
68
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 }
69
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 }
70
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 execution begins in the run() method and terminates when the run() method terminates
71
Thread: The run() method: Example ©Aditya Mathur. CS 180. Fall 2011. Week 12 public void run (){ // Must not have any parameters // Thread execution 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.
72
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 execution of the run() method and even after the completion of the run() method.
73
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.
74
Thread: Creation ©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);
75
Thread: Start of execution ©Aditya Mathur. CS 180. Fall 2011. Week 12 Execution of a thread must be started using the start() method for that thread. Here are two examples for starting threads one and two. one.start(); // Starts the execution of thread object one two.start(); // Starts the execution of thread object two
76
Thread: Waiting for completion ©Aditya Mathur. CS 180. Fall 2011. Week 12 You may wait for a thread to complete execution using the join() method as follows. try{ one.join(); // Wait for thread one to complete two.join(); // Wait for thread one to complete catch(Exception e){} The try-catch block is needed. More on this later!
77
Thread: Extracting results ©Aditya Mathur. CS 180. Fall 2011. Week 12 You may extract the outcome of a thread’s execution 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
78
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.
79
Example: Concurrent search ©Aditya Mathur. CS 180. Fall 2011. Week 12
80
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 sequentially.
81
Understanding the problem ©Aditya Mathur. CS 180. Fall 2011. Week 12 The problem is rather straightforward!
82
Search algorithm ©Aditya Mathur. CS 180. Fall 2011. Week 12 There are many search algorithms available. Given no information 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 until a match is found or all elements have been compared. If a match is found, the algorithm returns true, otherwise it returns false.
83
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]
84
Concurrent search: Array partitioned ©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
85
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.
86
Live demo ©Aditya Mathur. CS 180. Fall 2011. Week 12
87
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.
88
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}
89
Week 12: November 7-11, 2011. Hope you enjoyed this week! Questions? Contact your recitation instructor. Make full use of our office hours. ©Aditya Mathur. CS 180. Fall 2011. Week 12
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.