5 More sophisticated behavior

Slides:



Advertisements
Similar presentations
More Sophisticated Behaviour 1 Using library classes to implement more advanced functionality.
Advertisements

Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
More sophisticated behaviour Using library classes to implement some more advanced functionality.
Copyright by Scott GrissomCh 5 Sophisticated Behavior Slide 1 Java Class Library a very large collection of classes for you to use as needed the challenge.
More sophisticated behavior Using library classes to implement some more advanced functionality 4.0.
More Sophisticated Behaviour 2 Using library classes to implement more advanced functionality. Also … class ( static ) fields.
More sophisticated behavior Using library classes to implement some more advanced functionality 3.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Understanding class definitions Looking inside classes.
More sophisticated behavior Using library classes to implement some more advanced functionality.
JAVA LIBRARY CLASSES CITS Main concepts to be covered Using library classes: String, Math, Color Reading documentation Java 7 API is available.
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Java Packages and Libraries M Taimoor Khan
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
(c) University of Washington14-1 CSC 143 Java Collections.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 2.0.
More sophisticated behavior Using library classes to implement some more advanced functionality 5.0.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
Understanding class definitions
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 1.0.
More sophisticated behavior Using library classes to implement some more advanced functionality 5.0.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
1 COS 260 DAY 10 Tony Gauvin. 2 Agenda Questions? 4 th Mini quiz Today –Chapter 4 Assignment 2 Due Capstone Discussion Proposals Due Oct 15 No class on.
CS1054: Lecture 11 More Sophisticated Behavior (contd..)
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
1 COS 260 DAY 9 Tony Gauvin. 2 Agenda Questions? 3 rd Mini quiz –Good results ->All A’s –Threw out question on name overloading 4 th Mini quiz next class.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
Programming Fundamentals 2: Libraries/ F II Objectives – –utilize some useful Java libraries e.g. String, Scanner, HashMap, and Random.
Grouping objects Iterators, collections and the while loop Equality and Equality == and equals(…)
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
OOP (Java): Libraries/ OOP (Java) Objectives – –utilize some useful Java libraries e.g. String, Scanner, HashMap, and Random Semester.
Review. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Objects and Classes Objects and Classes –State.
More-Sophisticated Behavior Using library classes to implement some more advanced functionality 6.0.
BlueJ Chapter 5 More sophisticated behavior: Library classes and documentation.
1 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for-each PROS easy to use access to ALL items one-by-one ability to change the state.
Slides by Donald W. Smith
More-Sophisticated Behavior
Using the Java Collection Libraries COMP 103 # T2
for-each PROS CONS easy to use access to ALL items one-by-one
Objects First with Java CITS1001 week 4
9 Improving structure with inheritance
More Sophisticated Behavior
Libraries CITS1001.
JAVA COLLECTIONS LIBRARY
Chapter 5: Control Structures II
COS 260 DAY 7 Tony Gauvin.
Primitive Types Vs. Reference Types, Strings, Enumerations
COS 260 DAY 9 Tony Gauvin.
Week 6 Discussion Word Cloud.
More sophisticated behavior
Objects First with Java Introduction to collections
Understanding class definitions
COS 260 DAY 11 Tony Gauvin.
COS 260 DAY 8 Tony Gauvin.
Iteration Abstraction
Objects First with Java Introduction to collections
CSE 214 – Computer Science I More on Linked Lists
16 Strings.
Python Primer 1: Types and Operators
Understanding class definitions
Collections and iterators
F II 6. Using Libraries Objectives
Introduction to Object-Oriented Programming
Collections and iterators
Presentation transcript:

5 More sophisticated behavior Objektorienterad programmering d2, förel. 5 5 More sophisticated behavior Using library classes to implement some more advanced functionality BK Chap. 6 DAT050, 16/17, lp 1

Main concepts to be covered Objektorienterad programmering d2, förel. 5 Main concepts to be covered Maps and sets Random number generation Equality vs identity Class variables Constants Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

A Technical Support System Objektorienterad programmering d2, förel. 5 A Technical Support System A textual dialog system Simulates on-line computer helpdesk Idea based on ‘Eliza’ by Joseph Weizenbaum (MIT, 1960s) Explore tech-support-complete … Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Tech support The stupid @#*! system erased all my files Does the query contain known computer related keywords? Yes No Print a response containing keyword(s) from the query Print a random response from a list of standard answers Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

A simple ”knowledge base” Objektorienterad programmering d2, förel. 5 A simple ”knowledge base” Set of words String ”W1” ”Wi” ... ”Wn” ”W1 ... Wn” tokenize For some Wi: does the table contain Wi as a keyword? Response table key1 response1 ... keym responsem List of standard responses response1 ... responsem Yes, Wi = keyj => print responsej No: print random standard response Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Data structures String HashSet<String> Set of words ”W1 ... Wn” ”W1” ”Wi” ... ”Wn” HashMap<String,String> Response table key1 response1 ... keym responsem ArrayList<String> List of standard responses response1 ... responsem Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Main loop structure boolean finished = false; while(!finished) { do something if(exit condition) finished = true; else { do something more } A common iteration pattern. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Alternative loop structure Objektorienterad programmering d2, förel. 5 Alternative loop structure While ( true ) { do something if(exit condition) break; else { do something more } A common iteration pattern. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Main loop body String input = reader.getInput(); ... String response = responder.generateResponse(); System.out.println(response); Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 The exit condition String input = reader.getInput(); if(input.startsWith("bye")) break; Look for ‘startsWith’ in java.lang.String Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Some methods for Strings Objektorienterad programmering d2, förel. 5 Some methods for Strings contains startsWith indexOf substring toUpperCase trim split Beware: strings are immutable! Kolla StringBuffer och StringBuilder Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Random number generation Objektorienterad programmering d2, förel. 5 Random number generation The library class Random can be used to generate (pseudo) random numbers import java.util.Random; ... Random randomGenerator = new Random(); int index1 = randomGenerator.nextInt(); int index2 = randomGenerator.nextInt(100); int dieValue = randomGenerator.nextInt(6)+1; 0 ≤ randomGenerator.nextInt(n) < n Tärning: 35 Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Generating random responses Objektorienterad programmering d2, förel. 5 Generating random responses public Responder() { randomGenerator = new Random(); responses = new ArrayList<String>(); fillResponses(); } public void fillResponses() fill responses with a selection of response strings public String generateResponse() int index = randomGenerator.nextInt(responses.size()); return responses.get(index); Konstruktorn anropar en metod som gör resten av jobbet Borde denna vara privat? Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objects First with Java Sets and Maps Further library classes Set Map Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Using sets import java.util.HashSet; import java.util.Iterator; ... HashSet<String> mySet = new HashSet<String>(); mySet.add("one"); mySet.add("two"); mySet.add("three"); Iterator<String> it = mySet.iterator(); while(it.hasNext()) { call it.next() to get the next object do something with that object } Compare this to ArrayList code! Hur många”Two” finns det i mängden? I vilken ordning hamnar strängarna? I den ordning de sattes in? I bokstavsordning? Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Sets don’t store duplicates Objektorienterad programmering d2, förel. 5 Sets don’t store duplicates Example. String[] words = {"aaa","bb","aaa","ccc","d","aaa","bb","e","ccc"}; HashSet<String> set = new HashSet<String>(); for(String word : words) set.add(word); for(String s : set) System.out.println(s); program output bb aaa ccc e d in arbitrary order (HashSet) Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Tokenizing strings (Splitting a string into words) Objektorienterad programmering d2, förel. 5 Tokenizing strings (Splitting a string into words) public HashSet<String> getInput() { System.out.print("> "); String inputLine = reader.nextLine().trim().toLowerCase(); String[] wordArray = inputLine.split(); HashSet<String> words = new HashSet<String>(); for(String word : wordArray) words.add(word); return words; } Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Maps Maps are collections that contain pairs of values. Pairs consist of a key and a value. Lookup works by supplying a key, and retrieving a value. An example: a telephone book. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Using maps A map with Strings as keys and values :HashMap “Uno Holmer" “+46(0)317725730" “Peter Lundin" "+46(0)317722416" “Javaakuten" “999999" Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Using maps HashMap <String, String> phoneBook = new HashMap<String,String>(); phoneBook.put("Uno Holmer", "+46(0)317725730"); phoneBook.put("Arne Linde", "+46(0)317721683"); phoneBook.put("Javaakuten", "999999"); String phoneNumber = phoneBook.get("Javaakuten"); System.out.println(phoneNumber); Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Generating “smart” responses Objektorienterad programmering d2, förel. 5 Generating “smart” responses private HashMap<String,String> responseMap; ... public String generateResponse(HashSet<String> words) { for(String word : words) { String response = responseMap.get(word); if(response != null) return response; } return pickDefaultResponse(); } Words är de ord användaren skrev in i sin fråga Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Using containsKey private HashMap<String,String> responseMap; ... public String generateResponse(HashSet<String> words) { for(String word : words) { if ( responseMap.containsKey(word) ) return responseMap.get(word); } return pickDefaultResponse(); } Words är de ord användaren skrev in i sin fråga Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 List, Map and Set Alternative ways to group objects. Varying implementations available: ArrayList, LinkedList HashSet, TreeSet HashMap, TreeMap The first word reveals the underlying data representation (data structure). Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Code completion The BlueJ editor supports lookup of methods. Use Ctrl-space after a method-call dot to bring up a list of available methods. Use Return to select a highlighted method. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Code completion in BlueJ Objektorienterad programmering d2, förel. 5 Code completion in BlueJ Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Some further topics Equality vs identity Class variables Constants Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Side note: Equality vs identity Objektorienterad programmering d2, förel. 5 Side note: Equality vs identity A == B is true iff A and B refer to the same object A.equals(B) is true iff A and B refer to objects with equal content A == B implies A.equals(B) if desired, include more detailed discussion of identity vs equality here. (That's the next 5 slides, up to "Identity vs equality (Strings)". Skip these if this is not needed now. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Equality vs identity 1 :Person :Person 20 30 person1 person2 == is not true here (of course) person1 == person2 ? Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Equality vs identity 2 :Person :Person 20 20 person1 person2 == is still not true here (different objects, == tests identity) person1 == person2 ? Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Identity vs equality 3 :Person :Person 20 20 person1 person2 == is true now (same object) person1 == person2 ? Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 String equality tests identity if(input == "bye") { ... } if(input.equals("bye")) { Always use equals for testing text equality. tests equality if desired, include more detailed discussion of identity vs equality here. (That's the next 5 slides, up to "Identity vs equality (Strings)". Skip these if this is not needed now. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 String equality 1 String input = reader.getInput(); if ( input == "bye" ) { ... } == tests identity :String :String == ? "bye" "bye" == is still not true here (different objects, == tests identity) input  (may be) false! Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 String equality 2 String input = reader.getInput(); if ( input.equals("bye") ) { ... } equals tests equality :String :String ? equals "bye" "bye" == is still not true here (different objects, == tests identity) input  true! Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

The problem with Strings Objektorienterad programmering d2, förel. 5 The problem with Strings The compiler stores identical String literals in shared memory: The result is reference equality for apparently distinct String objects. Eg. ”Hello!” == ”Hello!” is true But this cannot be done for identical strings that arise outside the program’s code e.g., from user input. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Class variables and constants Objektorienterad programmering d2, förel. 5 Class variables and constants DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Class variables A class variable is shared between all instances of the class. In fact, it belongs to the class and exists independent of any instances. Designated by the static keyword. Public static variables are accessed via the class name; e.g. Thermometer.boilingPoint Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Class variables Tärning: 12 Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objektorienterad programmering d2, förel. 5 Constants A variable, once set, can have its value fixed. Designated by the final keyword. final int max = list.size(); Final fields must be set in their declaration or the constructor. Combing static and final is common. Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1

Objects First with Java Class constants static: class variable final: constant private static final int gravity = 3; Public visibility is less of an issue with final fields. Upper-case names often used for class constants: public static final int BOILING_POINT = 100; Objektorienterad programmering, DAT050, DAI2, 16/17, lp 1 DAT050, 16/17, lp 1