1 / 42

BlueJ Chapter 5

BlueJ Chapter 5. More sophisticated behavior: Library classes and documentation. Java constructs to be discussed in this chapter:. String ArrayList Random HashMap HashSet Iterator String Tokenizer Static final. 1. Review. Arraylist Useful class from the Java library

kiele
Download Presentation

BlueJ Chapter 5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. BlueJ Chapter 5 More sophisticated behavior: Library classes and documentation

  2. Java constructs to be discussed in this chapter: String ArrayList Random HashMap HashSet Iterator String Tokenizer Static final

  3. 1. Review • Arraylist • Useful class from the Java library • store an arbitrary number of objects • Knowing how to use the libraries is essential to becoming an advanced Java programmer • Too big to memorize, thousands of classes • Learn how to read the API • HOW it’s implemented doesn’t matter • ALL is well documented so others can use it

  4. This chapter’s project • A technical support system • DodgySoft software company • 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.

  5. Prototype tech-support1(the simplified version)

  6. Developing the system • The prototype support system starts out very dumb. • Always gives the same response • 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 • 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?

  8. 3. Interface vs. Implementation • 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. • Implementation = complete source code to define a class • If an interface is well written you don’t need to see the implementation.

  9. 4. String equality • Remember, if Word is a String • (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.

  10. Improving the system • First improvement: • Vary the responses • Start with random responses unrelated to user input • Create an ArrayList of possible string responses

  11. 5. Random numbers • import java.util.random; • // create an instance of the Random class • Random randGen; • randGen = new Random(); • int index –=randGen.nextInt(); • 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!

  12. Range of random numbers • Random numbers generated are >= -2,147,483,648 and <= 2,147,483,647 • nextInt(n) generates a number from 0 (inclusive) to n (exclusive)

  13. Add random to Responder class • Import java.util.Random • Declare a field of type Random • Declare a field of type ArrayList • Create the Random and ArrayList objects • Fill the ArrayList with some responses • Select and return a random phrase when generateResponse is called.

  14. 6. Review: ArrayLists • // import the package to use • import java.util.ArrayList; • // create a list • ArrayList<String> myList = new ArrayList<String>(); • // the size method returns the number of elements in the list • int size = myList.size(); • // the get method returns an element at an index • // you must cast to the type of result you want • String nthAnswer = myList.get(n); // no need to cast

  15. int index = randomGenerator.nextInt(responses.size()); return responses.get(index); int listSize = responses.size(); int index = randomGenerator.nextInt(listSize); return responses.get(index); Which is easier to read?

  16. 7. importing packages • we could just import java.util.*; • better to specify which classes are used • import java.util.Random; • import java.util.ArrayList: • all classes in java.lang are automatically imported. • these are the most used classes like String and System

  17. stop here • You’ve finished the notes for part 1 • Do the part 1 exercises.

  18. 8. Maps • A collection that stores key/value pairs. • Values can be looked up using the key. • Example: phonebook • key = name • value = 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

  19. 9. HashMap • a special kind of map. • put inserts an entry into the map • get retrieves a value for a given key • HashMap phoneBook = new HashMap(); • // add numbers to book • phoneBook.put(“Li Wei”, “(410) 335-1234”); • phoneBook.put(“Ann Day”, “(301) 555-1212”); • // look up a number • String s = (String) phoneBook.get(“Li Wei”);

  20. Improving tech support • map responses to key words to start with, just use single key words

  21. Goal for tech-support • User enters complete sentences • 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. • 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 • no specific order • no repetition of elements • must be able to: • add elements • retrieve elements

  23. 11. Java collections

  24. 12. Iterator • an object that allows you to iterate (travel) over all elements of a collection • import java.util.Iterator; • hasNext method returns true/false • next method gets the next object • good for accessing collections that don’t have an index • it keeps track and visits every element.

  25. example of an iterator • always starts at the beginning and moves to the end • in an ArrayList: • ArrayList myList = new ArrayList(); • Iterator it = myList.iterator(); • while(it.hasNext()){ • System.out.println(it.next()); • }

  26. 13.Using sets • import java.util.HashSet; • import java.util.Iterator; • add words from the input into the set • HashSet myset = new HashSet(); • mySet.add(word1); • mySet.add(word2); // how to get the words?

  27. 14. Tokenizing strings • StringTokenizer class • like an iterator • String input = readInputLine(); • HashSet words = new HashSet(); • StringTokenizer tk = new StringTokenizer(input); • while (tk.hasMoreTokens()) • words.add(tk.nextToken());

  28. Finishing tech support • When changing the input to produce a set of words instead of a single string: • must also adjust SupportSystem and Responder classes • the result of the getInput method is now a HashSet • the parameter into generateResponse is now a HashSet • if no words in the set are recognized, generate a random response.

  29. Documentation • A serious problem in real-world projects • 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. • The documentation should explain everything.

  30. 15. javadoc in BlueJ • Generate documentation function in main menu • Interface view option in editor shows a preview of the documentation for a single class.

  31. class documentation • should include • class name • overall purpose • version number • author’s name • documentation for each constructor and method

  32. documentation for each constructor and method • should include: • name of method • return type • parameter names and types • description of purpose of method • description of each parameter • description of value returned. • Additionally a Read Me file is usually included in each project.

  33. 16. javadoc comments • /** • this is a javadoc comment • */ • 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. • 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.

  35. 18. Public vs. private • Access modifiers • define the visibility of a field, constructor or method. • 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 • do the exercises before continuing to the ball project at the end of the chapter

  37. Ball project

  38. Altering the Ball Demo • Good practice to study these concepts • 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.

  39. 19. Class variables and constants • static variables exist one per CLASS. not one for each instance of the class. • // in bouncingBall • private static final int gravity = 3; • private int xPosition; • private int YPosition; • If 3 instances of Bouncing Balls are created • there will be one gravity variable • 3 xPositions and 3 yPositions • each ball has an individual x and y position, but all have the same gravity.

  40. Constants • private final int size = 10; • must be initialized when declared. • are usually class variables • private static final int size = 10;

  41. Summary • You should be able to read and write class library descriptions • Know essential classes from the library • Use javadoc for standardized documentation

  42. interface implementation map set javadoc access modifier information hiding coupling class variable static constant final 20. Vocabulary

More Related