Download presentation
Presentation is loading. Please wait.
Published byMilton King Modified over 8 years ago
1
BlueJ Chapter 5 More sophisticated behavior: Library classes and documentation
2
Java constructs to be discussed in this chapter: StringArrayListRandomHashMapHashSetIterator String Tokenizer Staticfinal
3
1. Review Arraylist Arraylist Useful class from the Java library Useful class from the Java library store an arbitrary number of objects store an arbitrary number of objects Knowing how to use the libraries is essential to becoming an advanced Java programmer Knowing how to use the libraries is essential to becoming an advanced Java programmer Too big to memorize, thousands of classes Too big to memorize, thousands of classes Learn how to read the API Learn how to read the API HOW it’s implemented doesn’t matter HOW it’s implemented doesn’t matter ALL is well documented so others can use it ALL is well documented so others can use it
4
This chapter’s project A technical support system A technical support system DodgySoft software company DodgySoft software company Decided to get rid of people answering phones for tech support and replace them with an online support system. Decided to get rid of people answering phones for tech support and replace them with an online support system. The program holds a dialog with the user, responding to questions. The program holds a dialog with the user, responding to questions.
5
Prototype tech-support1 (the simplified version) Support System Input Reader Responder
6
Developing the system The prototype support system starts out very dumb. The prototype support system starts out very dumb. Always gives the same response Always gives the same response First understand how it works, then improve upon it. First understand how it works, then improve upon it.
7
2. Refer to the API One method used in the start method of the SupportSystem class is startsWith One method used in the start method of the SupportSystem class is startsWith Find documentation for the String class for a description of how the method works Find documentation for the String class for a description of how the method works (Appendix F of the BlueJ book tells how to set up BlueJ to access a local copy of the API to run faster, can we do this? (Appendix F of the BlueJ book tells how to set up BlueJ to access a local copy of the API to run faster, can we do this?
8
3. Interface vs. Implementation Interface = describes what a class does and how it can be used Interface = describes what a class does and how it can be used Please note: the word interface is also used a number of different ways in Java, like the I in GUI, or the interface type of class definition. Please note: the word interface is also used a number of different ways in Java, like the I in GUI, or the interface type of class definition. Implementation = complete source code to define a class Implementation = complete source code to define a class If an interface is well written you don’t need to see the implementation. If an interface is well written you don’t need to see the implementation.
9
4. String equality Remember, if Word is a String Remember, if Word is a String (Word = = “bye”) is true if the String Word and the String “bye” occupy the same memory location (Word = = “bye”) is true if the String Word and the String “bye” occupy the same memory location Word.equals(“bye”) is true if the 2 strings have the same content. Word.equals(“bye”) is true if the 2 strings have the same content.
10
Improving the system First improvement: First improvement: Vary the responses Vary the responses Start with random responses unrelated to user input Start with random responses unrelated to user input Create an ArrayList of possible string responses Create an ArrayList of possible string responses
11
5. Random numbers import java.util.random; import java.util.random; // create an instance of the Random class // create an instance of the Random class Random randGen; Random randGen; randGen = new Random(); randGen = new Random(); int index –=randGen.nextInt(); int index –=randGen.nextInt(); System.out.println(index); System.out.println(index); Note: Only create one instance of Random and store it within a class definition. Don’t create a new Random instance every time you want a new number or it won’t be very random! Note: Only create one instance of Random and store it within a class definition. Don’t create a new Random instance every time you want a new number or it won’t be very random!
12
Range of random numbers Random numbers generated are >= -2,147,483,648 and = -2,147,483,648 and <= 2,147,483,647 nextInt(n) generates a number from 0 (inclusive) to n (exclusive) nextInt(n) generates a number from 0 (inclusive) to n (exclusive)
13
Add random to Responder class Import java.util.Random Import java.util.Random Declare a field of type Random Declare a field of type Random Declare a field of type ArrayList Declare a field of type ArrayList Create the Random and ArrayList objects Create the Random and ArrayList objects Fill the ArrayList with some responses Fill the ArrayList with some responses Select and return a random phrase when generateResponse is called. Select and return a random phrase when generateResponse is called.
14
6. Review: ArrayLists // import the package to use // import the package to use import java.util.ArrayList; import java.util.ArrayList; // create a list // create a list ArrayList myList = new ArrayList (); ArrayList myList = new ArrayList (); // the size method returns the number of elements in the list // the size method returns the number of elements in the list int size = myList.size(); int size = myList.size(); // the get method returns an element at an index // the get method returns an element at an index // you must cast to the type of result you want // you must cast to the type of result you want String nthAnswer = myList.get(n); // no need to cast String nthAnswer = myList.get(n); // no need to cast
15
Which is easier to read? int index = randomGenerator.nextInt(responses.size()); int index = randomGenerator.nextInt(responses.size()); return responses.get(index); return responses.get(index); int listSize = responses.size(); int listSize = responses.size(); int index = randomGenerator.nextInt(listSize); int index = randomGenerator.nextInt(listSize); return responses.get(index); return responses.get(index);
16
7. importing packages we could just import java.util.*; we could just import java.util.*; better to specify which classes are used better to specify which classes are used import java.util.Random; import java.util.Random; import java.util.ArrayList: import java.util.ArrayList: all classes in java.lang are automatically imported. all classes in java.lang are automatically imported. these are the most used classes like String and System these are the most used classes like String and System
17
stop here You’ve finished the notes for part 1 You’ve finished the notes for part 1 Do the part 1 exercises. Do the part 1 exercises.
18
8. Maps A collection that stores key/value pairs. A collection that stores key/value pairs. Values can be looked up using the key. Values can be looked up using the key. Example: phonebook Example: phonebook key = name key = name value = phone number value = phone number look up a name to get a phone number look up a name to get a phone number does not use an index (position of the entry in the book) to find info, uses alphabetical order of keys does not use an index (position of the entry in the book) to find info, uses alphabetical order of keys
19
9. HashMap a special kind of map. a special kind of map. put inserts an entry into the map put inserts an entry into the map get retrieves a value for a given key get retrieves a value for a given key HashMap phoneBook = new HashMap(); HashMap phoneBook = new HashMap(); // add numbers to book // add numbers to book phoneBook.put(“Li Wei”, “(410) 335-1234”); phoneBook.put(“Li Wei”, “(410) 335-1234”); phoneBook.put(“Ann Day”, “(301) 555-1212”); phoneBook.put(“Ann Day”, “(301) 555-1212”); // look up a number // look up a number String s = (String) phoneBook.get(“Li Wei”); String s = (String) phoneBook.get(“Li Wei”);
20
Improving tech support map responses to key words map responses to key words If they say: Respond: slow Upgrading your hardware should solve performance problems bug Our software engineers are working on the problem right now. expensive Our cost is very competitive, Have you really noticed our features? Anything else Otherwise, generate a random response to start with, just use single key words
21
Goal for tech-support User enters complete sentences User enters complete sentences input will not be stored as a single string, but a set of strings containing each word in the question input will not be stored as a single string, but a set of strings containing each word in the question Matching responses are selected if any keywords are recognized in the question. Matching responses are selected if any keywords are recognized in the question. the set of strings (words in the question) is sent to the responder to check every word and generate a response. the set of strings (words in the question) is sent to the responder to check every word and generate a response.
22
10. Set a collection that stores each individual element a collection that stores each individual element no specific order no specific order no repetition of elements no repetition of elements must be able to: must be able to: add elements add elements retrieve elements retrieve elements
23
11. Java collections General collection type Construct used List Keeps things in order ArrayList Map Key to value connection HashMap Set Unique elements in no order HashSet
24
12. Iterator an object that allows you to iterate (travel) over all elements of a collection an object that allows you to iterate (travel) over all elements of a collection import java.util.Iterator; import java.util.Iterator; hasNext method returns true/false hasNext method returns true/false next method gets the next object next method gets the next object good for accessing collections that don’t have an index good for accessing collections that don’t have an index it keeps track and visits every element. it keeps track and visits every element.
25
example of an iterator always starts at the beginning and moves to the end always starts at the beginning and moves to the end in an ArrayList: in an ArrayList: ArrayList myList = new ArrayList(); ArrayList myList = new ArrayList(); Iterator it = myList.iterator(); Iterator it = myList.iterator(); while(it.hasNext()){ while(it.hasNext()){ System.out.println(it.next()); System.out.println(it.next()); }
26
13.Using sets import java.util.HashSet; import java.util.HashSet; import java.util.Iterator; import java.util.Iterator; add words from the input into the set add words from the input into the set HashSet myset = new HashSet(); HashSet myset = new HashSet(); mySet.add(word1); mySet.add(word1); mySet.add(word2); // how to get the words? mySet.add(word2); // how to get the words?
27
14. Tokenizing strings StringTokenizer class StringTokenizer class like an iterator like an iterator String input = readInputLine(); String input = readInputLine(); HashSet words = new HashSet(); HashSet words = new HashSet(); StringTokenizer tk = new StringTokenizer(input); StringTokenizer tk = new StringTokenizer(input); while (tk.hasMoreTokens()) while (tk.hasMoreTokens()) words.add(tk.nextToken()); words.add(tk.nextToken());
28
Finishing tech support When changing the input to produce a set of words instead of a single string: When changing the input to produce a set of words instead of a single string: must also adjust SupportSystem and Responder classes must also adjust SupportSystem and Responder classes the result of the getInput method is now a HashSet the result of the getInput method is now a HashSet the parameter into generateResponse is now a HashSet the parameter into generateResponse is now a HashSet if no words in the set are recognized, generate a random response. if no words in the set are recognized, generate a random response.
29
Documentation A serious problem in real-world projects A serious problem in real-world projects A commercial application may have hundreds of thousands of lines of code in thousands of classes A commercial application may have hundreds of thousands of lines of code in thousands of classes Nobody should have to read your actual code to understand how it works. Nobody should have to read your actual code to understand how it works. The documentation should explain everything. The documentation should explain everything.
30
15. javadoc in BlueJ Generate documentation function in main menu Generate documentation function in main menu Interface view option in editor shows a preview of the documentation for a single class. Interface view option in editor shows a preview of the documentation for a single class.
31
class documentation should include should include class name class name overall purpose overall purpose version number version number author’s name author’s name documentation for each constructor and method documentation for each constructor and method
32
documentation for each constructor and method should include: should include: name of method name of method return type return type parameter names and types parameter names and types description of purpose of method description of purpose of method description of each parameter description of each parameter description of value returned. description of value returned. Additionally a Read Me file is usually included in each project. Additionally a Read Me file is usually included in each project.
33
16. javadoc comments /** /** this is a javadoc comment this is a javadoc comment */ */ key symbols starting with @ are recognized key symbols starting with @ are recognized @version@author@param@return
34
17. Good programming practices To ensure better modularization of an application, internal detail of a class’s implementation should be hidden from other classes. This is information hiding. To ensure better modularization of an application, internal detail of a class’s implementation should be hidden from other classes. This is information hiding. If changes in one part of a program do not make it necessary to also make changes in another part of the program it is weak coupling or loose coupling. If changes in one part of a program do not make it necessary to also make changes in another part of the program it is weak coupling or loose coupling. This is good because it makes programs easier to maintain and upgrade. This is good because it makes programs easier to maintain and upgrade.
35
18. Public vs. private Access modifiers Access modifiers define the visibility of a field, constructor or method. define the visibility of a field, constructor or method. things marked private are within the implementation and don’t need documentation externally. (like javadoc) things marked private are within the implementation and don’t need documentation externally. (like javadoc)
36
stop here you’ve finished the notes for part 2 you’ve finished the notes for part 2 do the exercises before continuing to the ball project at the end of the chapter do the exercises before continuing to the ball project at the end of the chapter
37
Ball project Ball Demo 2 ways to produce graphical output on canvas Bouncing Ball behavior of a bouncing ball Canvas Provides a window to draw on
38
Altering the Ball Demo Good practice to study these concepts Good practice to study these concepts The Canvas class should not need any modification The Canvas class should not need any modification A canvas can be used by creating an instance and making it visible using the setVisible method. A canvas can be used by creating an instance and making it visible using the setVisible method.
39
19. Class variables and constants static variables exist one per CLASS. not one for each instance of the class. static variables exist one per CLASS. not one for each instance of the class. // in bouncingBall // in bouncingBall private static final int gravity = 3; private static final int gravity = 3; private int xPosition; private int xPosition; private int YPosition; private int YPosition; If 3 instances of Bouncing Balls are created If 3 instances of Bouncing Balls are created there will be one gravity variable there will be one gravity variable 3 xPositions and 3 yPositions 3 xPositions and 3 yPositions each ball has an individual x and y position, but all have the same gravity. each ball has an individual x and y position, but all have the same gravity.
40
Constants private final int size = 10; private final int size = 10; must be initialized when declared. must be initialized when declared. are usually class variables are usually class variables private static final int size = 10; private static final int size = 10;
41
Summary You should be able to read and write class library descriptions You should be able to read and write class library descriptions Know essential classes from the library Know essential classes from the library Use javadoc for standardized documentation Use javadoc for standardized documentation
42
20. Vocabulary interface interface implementation implementation map map set set javadoc javadoc access modifier access modifier information hiding information hiding coupling coupling class variable class variable static static constant constant final final
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.