Main loop structure. A Technical Support System. The exit condition. Main loop body

Similar documents
CITS1001 week 6 Libraries

More sophisticated behaviour

5 More sophisticated behavior

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling 2

More Sophisticated Behaviour

More Sophisticated Behaviour

More Sophisticated Behaviour

Text User Interfaces. Keyboard IO plus

Grouping objects. Main concepts to be covered

Some miscellaneous concepts

CITS1001 week 4 Grouping objects

Topic 10: The Java Collections Framework (and Iterators)

OBJECT INTERACTION CITS1001

Package: java.util It generates random numbers An instance is created by using one of the two constructors:

More sophisticated behaviour Lecture 09

Grouping objects. The requirement to group objects

Inf1-OOP. Encapsulation and Collections. Perdita Stevens, adapting earlier version by Ewan Klein. March 2, School of Informatics

Interfaces, collections and comparisons

Inf1-OOP. Encapsulation. Object Oriented Programming. Encapsulation Accessing Data Immutability. Encapsulation and Collections.

Java Classes and Objects

CS251L REVIEW Derek Trumbo UNM

Ticket Machine Project(s)

6.092 Introduction to Software Engineering in Java January (IAP) 2009

UNDERSTANDING CLASS DEFINITIONS CITS1001

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Inf1-OP. Collections. Perdita Stevens, adapting earlier version by Ewan Klein. January 9, School of Informatics

1st Semester Examinations CITS1001 3

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

Rigidity of arrays. Inf1-OP. ArrayList. ArrayList: Methods. Declaration. Collections

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional)

Algorithms. Produced by. Eamonn de Leastar

5/23/2015. Core Java Syllabus. VikRam ShaRma

Inf1-OP. Collections. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 6, School of Informatics

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

Grouping Objects (I)

Unit5: Packages and abstraction. Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15

Garbage Collection (1)

CST141 Thinking in Objects Page 1

Guessing Game with Objects

Unit5: Packages and abstraction

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

Index COPYRIGHTED MATERIAL

Scope of this lecture. Repetition For loops While loops

4. Enhancing a class: Room. The Java platform. Java APIs. M1G413283: Introduction to Programming 2

1. Suppose you are using a HashMap<String,Integer>. What is the runtime of put and get assuming you have a reasonable hash function?

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

//instance variables //methods. Foo x = new Foo(); Interface: also a type of objects public interface Bar {

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Searching and Strings. IST 256 Application Programming for Information Systems

Computational Expression

Inheritance and Interfaces

Object Oriented Design: Identifying Objects

ArrayList. Introduction. java.util.arraylist

Software Practice 1 - OOP (3) API Access Control Review Packages Java API Documentation

Introduction to Computer Science I

Collections, Maps and Generics

Set<Integer> s = new TreeSet<Integer>(); s.add( 7 ); s.add( 7 ); System.out.println( s.size() );

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Understanding class definitions. Looking inside classes (based on lecture slides by Barnes and Kölling)

Building Java Programs

Lesson 2.4 Arraylist

MIT AITI Lecture 18 Collections - Part 1

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Software Design Models, Tools & Processes. Lecture 6: Transition Phase Cecilia Mascolo

3 Getting Started with Objects

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Programming II (CS300)

Classes and Objects. COMP1400/INFS1609 Week 8. Monday, 10 September 12

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Collections. James Brucker

CSC 222: Object-Oriented Programming. Spring 2013

Exploring the Java API, Packages & Collections

CS2110: Software Development Methods. Maps and Sets in Java

DEV2QA PDT 1.1. Feature Name : Code Completion Module name : PHPCompletionEngine

Understanding class definitions

Software Practice 1 - OOP (3) API

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

CS111: PROGRAMMING LANGUAGE II

Java for Interfaces and Networks (DT3010, HT11)

Week 4, Wednesday (Spring 2015). Dr. Yoder. Sec 051. Page 1 of 5

In this lecture Simple List Algorithms

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12

JAVA: A Primer. By: Amrita Rajagopal

ArrayLists. Chapter 12.1 in Savitch

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Lecture 9: Lists. MIT-AITI Kenya 2005

Java for Interfaces and Networks (DT3029)

CSC 222: Object-Oriented Programming. Spring 2017

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 2 EXAMINATIONS 2013/2014 CI101/CI101H. Programming

More on collec)ons and sor)ng

Final Exam CS 251, Intermediate Programming December 13, 2017

PIC 20A Collections and Data Structures

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

INTRODUCTION TO DATA AND PROCEDURE

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

Advanced Programming Languages Effective Java Item 1. Spring 2015 Chungnam National Univ Eun-Sun Cho

Objects First with Java A Practical Introduction using BlueJ

What is the Java Collections Framework?

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

Transcription:

Main concepts to be covered More sophisticated behavior Using library classes Reading documentation Using library classes to implement some more advanced functionality 5.0 2 The Java class library Thousands of classes. Tens of thousands of methods. Many useful classes that make life much easier. Library classes are often interrelated. Arranged into packages. Working with the library A competent Java programmer must be able to work with the libraries. You should: know some important classes by name; know how to find out about other classes. Remember: we only need to know the interface, not the implementation. 3 4

A Technical Support System Main loop structure A textual, interactive dialog system Idea based on Eliza by Joseph Weizenbaum (MIT, 1960s) Explore tech-support-complete boolean finished = false; while(!finished) { do something if(exit condition) { finished = true; else { do something more A common iteration pattern. 5 6 Main loop body The exit condition String input = reader.getinput();... String response = responder.generateresponse(); System.out.println(response); String input = reader.getinput(); if(input.startswith("bye")) { finished = true; Where does startswith come from? What is it? What does it do? How can we find out? 7 8

Reading class documentation Documentation of the Java libraries in HTML format; Readable in a web browser Class API: Application Programmers Interface Interface description for all library classes 9 10 Interface vs implementation Interface vs implementation The documentation includes the name of the class; a general description of the class; a list of constructors and methods return values and parameters for constructors and methods a description of the purpose of each constructor and method The documentation does not include private fields (most fields are private) private methods the bodies (source code) of methods the implementation of the class the interface of the class 11 12

Documentation for startswith Methods from String startswith public boolean startswith(string prefix) Tests if this string starts with the specified prefix. Parameters: prefix - the prefix. Returns: true if the ; false otherwise contains endswith indexof substring touppercase trim Beware: strings are immutable! 13 14 Using library classes Packages and import Classes organized into packages. Classes from the library must be imported using an import statement (except classes from the java.lang package). They can then be used like classes from the current project. Single classes may be imported: import java.util.arraylist; Whole packages can be imported: import java.util.*; Importation does not involve source code insertion. 15 16

Using Random Selecting random responses The library class Random can be used to generate random numbers import java.util.random;... Random rand = new Random();... int num = rand.nextint(); int value = 1 + rand.nextint(100); int index = rand.nextint(list.size()); 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); 17 18 Parameterized classes Parameterized classes The documentation includes provision for a type parameter: ArrayList<E> These type names reappear in the parameters and return types: E get(int index) boolean add(e e) The types in the documentation are placeholders for the types we use in practice: An ArrayList<TicketMachine> actually has methods: TicketMachine get(int index) boolean add(ticketmachine e) 19 20

Review Java has an extensive class library. A good programmer must be familiar with the library. The documentation tells us what we need to know to use a class (its interface). Some classes are parameterized with additional types. Parameterized classes are also known as generic classes or generic types. More sophisticated behavior Using library classes to implement some more advanced functionality 21 Main concepts to be covered Using sets import java.util.hashset; Further library classes Set Map Writing documentation javadoc... HashSet<String> myset = new HashSet<String>(); myset.add("one"); myset.add("two"); myset.add("three"); for(string element : myset) { do something with element Compare with code for an ArrayList! 23 24

Tokenising Strings 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; 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. Example: a telephone book. 25 26 Using maps Using maps A map with strings as keys and values :HashMap "Charles Nguyen" "(531) 9392 4587" "Lisa Jones" "(402) 4536 4674" "William H. Smith" "(998) 5488 0123" HashMap <String, String> phonebook = new HashMap<String, String>(); phonebook.put("charles Nguyen", "(531) 9392 4587"); phonebook.put("lisa Jones", "(402) 4536 4674"); phonebook.put("william H. Smith", "(998) 5488 0123"); String phonenumber = phonebook.get("lisa Jones"); System.out.println(phoneNumber); 27 28

List, Map and Set Writing class documentation Alternative ways to group objects. Varying implementations available: ArrayList, LinkedList HashSet, TreeSet But HashMap is unrelated to HashSet, despite similar names. The second word reveals organizational relatedness. Your own classes should be documented the same way library classes are. Other people should be able to use your class without reading the implementation. Make your class a potential 'library class'! 29 30 Elements of documentation Elements of documentation Documentation for a class should include: the class name a comment describing the overall purpose and characteristics of the class a version number the authors names documentation for each constructor and each method The documentation for each constructor and method should include: the name of the method the return type the parameter names and types a description of the purpose and function of the method a description of each parameter a description of the value returned 31 32

javadoc javadoc Class comment: /** * The Responder class represents a response * generator object. It is used to generate an * automatic response. * * @author Michael Kölling and David J. Barnes * @version 1.0 (2011.07.31) */ Method comment: /** * Read a line of text from standard input (the text * terminal), and return it as a set of words. * * @param prompt A prompt to print to screen. * @return A set of Strings, where each String is * one of the words typed by the user */ public HashSet<String> getinput(string prompt) {... 33 34 Public vs private Public elements are accessible to objects of other classes: Fields, constructors and methods Fields should not be public. Private elements are accessible only to objects of the same class. Only methods that are intended for other classes should be public. Information hiding Data belonging to one object is hidden from other objects. Know what an object can do, not how it does it. Information hiding increases the level of independence. Independence of modules is important for large systems and maintenance. 35 36

Code completion Code completion in BlueJ 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. 37 38 Review Java has an extensive class library. A good programmer must be familiar with the library. The documentation tells us what we need to know to use a class (interface). The implementation is hidden (information hiding). We document our classes so that the interface can be read on its own (class comment, method comments). Class and constant variables 39

Class variables 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 41 42 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. 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; 43 44