Survey #2. Teen Talk Barbie TM Reloaded. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Partially Filled Arrays ArrayLists

Similar documents
Survey #2. Variable Scope. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings. Scope Static.

Last Week: Organizing Data. Last Week: Parallel Arrays. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Survey #2. Assignment #3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings. Static Interface Types.

Survey #2. Programming Assignment 3. Final Exam. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Survey #2. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Midterms Save the Dates!

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Midterms Save the Dates!

Midterms Save the Dates!

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Using Classes and Objects. Lecture 7. Midterms Save the Dates! Extra Credit Survey

Midterms Save the Dates!

Midterms Save the Dates!

Midterms Save the Dates!

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Midterms Save the Dates!

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

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

PeerWise Study. Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Constants Using Classes and Objects

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

Midterms Save the Dates!

CS 121 Intro to Programming:Java - Lecture 2. Professor Robert Moll (+ TAs) CS BLDG

Survey #3. Final Exam. Today is totally optional! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings.

! This week: Chapter 6 all ( ) ! Formal parameter: in declaration of class. ! Actual parameter: passed in when method is called

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Administrative Stuff CIS Last Time. Midterm 2 today in-lab this week dups. Assignment 10. November 27, 2018

CS 121 Intro to Programming:Java - Lecture 2. Professor Robert Moll (+ TAs) CS BLDG

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

CIS November 27, 2018

Java Classes - Using your classes. How the classes you write are being used

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

Express Yourself. Writing Your Own Classes

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

CS 161: Object Oriented Problem Solving

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

BCIS 3630 Dr. GUYNES SPRING 2018 TUESDAY SECTION [JAN version] GRADER COURSE WEBSITE

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

CS 241 Data Organization. August 21, 2018

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner

CS 231 Data Structures and Algorithms, Fall 2016

Lab 1: Setup 12:00 PM, Sep 10, 2017

Lesson 5C MyClass Methods. By John B. Owen All rights reserved 2011, revised 2014

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

CS 455 Midterm Exam 1 Fall 2010 [Bono] Sept. 29, 2010

Prelim 1. CS 2110, 13 March 2018, 5:30 PM Total Question Name Short answer

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Advanced Object Oriented Programming EECS2030Z

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Midterms Save the Dates!

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

Java Basics Lecture: January 26, 2012 (On-line Lecture 1)

Tips from the experts: How to waste a lot of time on this assignment

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

University of Massachusetts Amherst, Electrical and Computer Engineering

Computer Science II Data Structures

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

Adam Blank Lecture 3 Autumn 2016 CSE 143. Computer Programming II

CSE 142. Lecture 1 Course Introduction; Basic Java. Portions Copyright 2008 by Pearson Education

Tips from the experts: How to waste a lot of time on this assignment

CSE 143. More ArrayIntList; pre/post; exceptions; debugging. Computer Programming II. CSE 143: Computer Programming II

APCS Semester #1 Final Exam Practice Problems

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

CS/ENGRD 2110 SPRING Lecture 5: Local vars; Inside-out rule; constructors

CSE 143: Computer Programming II Summer 2015 HW6: 20 Questions (due Thursday, August 13, :30pm)

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Computer Science II Lecture 1 Introduction and Background

CS 251 Intermediate Programming Coding Standards

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

G51PGP Programming Paradigms. Lecture OO-4 Aggregation

Midterms Save the Dates!

CS 170 Java Programming 1. Week 12: Creating Your Own Types

CSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, :30pm)

Overview. Lab 5 Methods and Parameters

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics

CSSE 220. Intro to Java Graphics. Check out IntroToJavaGraphics and BiggestFan projects from SVN

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

! Midterm 2: Thu Mar 16, 6:30pm (TODAY!) ! Woodward 2. ! hour-long exam, reserve 6:30-8 time slot. ! no labs/tutorials this week. ! Bunny.

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

CS/ENGRD 2110 SPRING Lecture 3: Fields, getters and setters, constructors, testing

QUIZ. What is wrong with this code that uses default arguments?

Outline. Intro. Week 1, Fri Jan 4. What is CG used for? What is Computer Graphics? University of British Columbia CPSC 314 Computer Graphics Jan 2013

Intro. Week 1, Fri Jan 4

COE318 Lecture Notes Week 6 (Oct 10, 2011)

ASSIGNMENT 5 Objects, Files, and a Music Player

Inheritance and Interfaces

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

COE 212 Engineering Programming. Welcome to the Final Exam Tuesday December 15, 2015

CS 351 Design of Large Programs Coding Standards

1. The Normal Distribution, continued

class objects instances Fields Constructors Methods static

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Transcription:

University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Partially Filled Arrays ArrayLists Do-It-Yourself ArrayLists Scope Static Readings This Week: Ch 8.3-8.8 and into Ch 9.1-9.3 (Ch 9.3-9.8 and Ch 11.1-11.3 in old 2 nd ed) (Reminder: Readings are absolutely vital for learning this stuff!) Lecture 18 Reusing some slides by Margaret Dulat and Joe Luk Labs and Tutorials This Week: Lab #8 A catch-up lab Survey #2 Dr. Ben Yu s second survey for you all is up on WebCT now. Completely optional But, there s a bit of extra credit for doing all three surveys by their respective deadlines! (I think the deadline for this one is March 22, but check on WebCT to be sure.) Learning Goals By the end of class today you will be able to Read and write programs that use partially-filled arrays (in the typical, idiomatic manner). Read and write programs that use Java s ArrayList class. Implement your own ArrayList class. Figure out exactly which declarations (variables, methods) are visible from which parts of a program. Explain what static means in Java programs and why you might want to use static methods and fields. Teen Talk Barbie TM Reloaded A few lectures back, we wrote a program that learns some phrases and prints them back at random (inspired by Mattel s Teen Talk Barbie TM doll). The goal was to have a fun example to introduce arrays. But the programming style wasn t very good. Better to create a TalkingDoll class 1

TalkingDoll Class Constructor that specifies name and maximum vocabulary size. Getters/Setters for the name. A method to add phrases to the doll. A method to get a random phrase back. Partially Filled Arrays Arrays have a fixed size, but often we want to hold a variable number of items. A Very Common Solution: Make an array bigger than you need. Have an int variable to keep track of what you are actually using. Partially Filled Arrays Arrays have a fixed size, but often we want to hold a variable number of items. A Very Common Solution: Make an array bigger than you need. Have an int variable to keep track of what you are actually using. Partially Filled Arrays Arrays have a fixed size, but often we want to hold a variable number of items. A Very Common Solution: Make an array bigger than you need. Have an int variable to keep track of what you are actually using. acount 2 a 3 1 a 3 1 Partially Filled Arrays A Very Common Solution: Your code must keep count variable up-to-date! Good to keep these private, so your methods can always do the right thing. (This is an example of a class or object invariant.) acount 2 a 3 1 Teen Talk Barbie TM Reloaded A few lectures back, we wrote a program that learns some phrases and prints them back at random (inspired by Mattel s Teen Talk Barbie TM doll). The goal was to have a fun example to introduce arrays. But the programming style wasn t very good. Better to create a TalkingDoll class 2

TalkingDoll Class Constructor that specifies name and maximum vocabulary size. Getters/Setters for the name. A method to add phrases to the doll. A method to get a random phrase back. Java s ArrayList Class What if you don t know (or want to force) a fixed maximum size in advance? Java has an ArrayList class for this case: import java.util.arraylist Declare: ArrayList<String> phrases = new ArrayList<String>(); Java s ArrayList Class What if you don t know (or want to force) a fixed maximum size in advance? Java has an ArrayList class for this case: import java.util.arraylist Declare: ArrayList<type> type phrases = new ArrayList<type>(); type Methods: int size() void add(<type> newvalue) <type> get(int index) void set(int index, <type> newvalue) <type> can be any object type. See Ch 7.2. TalkingDoll with ArrayLists Let s redo the TalkingDoll class using ArrayLists Do-It-Yourself ArrayLists ArrayLists are nothing magical! (OK, the generic <type> stuff is kind of magic.) It s just a class. If we fix the type of the elements (e.g., have an ArrayList of String), you know enough to write your own version. But how do you allow arrays to grow? Real-Life Analogy: Moving Homes A house (or condo, apartment, etc.) has a fixed size. What happens when your family grows and you need more space? 3

Real-Life Analogy: Moving Homes A house (or condo, apartment, etc.) has a fixed size. What happens when your family grows and you need more space? Answer: You buy a bigger place, and then you pack up and move all your stuff to the new place, and get rid of your old home. An array has a fixed size. What happens when your list grows and you need more space? newa newa 3 newa 3 1 4

newa 3 1 4 newa 3 1 4 1 a.length 8 a a.length 8 (garbage collection) newa 3 1 4 1 newa 3 1 4 1 (garbage collection) a MyStringArrayList Let s create a MyStringArrayList class. Methods: int size() void add(string newstring) String get(int index) a.length 8 3 1 4 1 5

Scope tells you which declarations you can see from which points in the program. The scope of a variable is the places in the program where the variable can be accessed. Or you can think of scope as the places where you can see some variable. (Think scope meaning extent, as in the scope of my legal authority or the scope of the inquest. Not scope as in telescope or scoping out the beach. The world is broken up into packages. import lets you see public stuff from other packages. Or you can give full name, e.g., java.util.scanner Other than that, can t see inside other packages import java.util.random; Random foo = new Random(); Packages contain classes Within a package, everyone can see all classes and non-private stuff within classes TalkingDoll a = new TalkingDoll(); System.out.println(a.getName()); System.out.println(a.name); Packages contain classes Within a package, everyone can see all classes and non-private stuff within classes TalkingDoll a = new TalkingDoll(); System.out.println(a.getName()); System.out.println(a.name); The variable name is private in the TalkingDoll class! Classes contain methods and fields All methods can see other methods and fields in same class public void setlabscore(int labnum, double score) { labscores[labnum-1] = score; computetotallabscore(); Methods contain statements, executed one-by-one You can see declarations that happened already Parameters are like declarations that happen at start of method. Curly braces define a compound statement, which limits scope public static void main(string[] args) { int a = 0; System.out.println(args[0]); int b = 2*a; int a = 3; // Not OK! b = c+a; // Not OK! -- can t see c int c; 6

Compound statement limits scope You can see out, but not in. public static void main(string[] args) { int a = 0; int b = 0; { // start of a block int a = 2; // Not OK! a already declared int c = 2; System.out.println(c); // prints 2 System.out.println(a); // prints 0 System.out.println(c); // Not OK! int c = 2; // OK Compound statement limits scope for loop is special: variables declared in header are treated as if declared inside loop body public static void main(string[] args) { int a = 0; int b = 0; for (int c=0; c < 3; c++) { // start of a block int a; System.out.println(c); // OK System.out.println(c); // Not OK! : Shadowing Local variable declarations wins over instance variable declarations. private static int a = 0; public static void main(string[] args) { int b = 0; { // start of a block int a = 2; // OK! Shadows other a int c = a; System.out.println(c); // prints 2 System.out.println(a); // prints 0 System.out.println(c); // Not OK! int c = 2; // OK -- Summary The world is broken up into packages. import lets you see public stuff from other packages. Or you can give full name, e.g., java.util.scanner Packages contain classes Within a package, everyone can see all classes and non-private stuff within classes Classes contain methods and fields All methods can see other methods and fields in same class Methods contain statements, executed one-by-one You can see declarations that happened already Parameters are like declarations that happen at start of method. Curly braces define a compound statement, which limits scope Compound statement limits scope You can see out, but not in. for loop is special: variables declared in header are visible only inside the loop Questions The Meaning of static From our very first Java program, we had: public static void main (String[] args) But what does static mean? 7

Review: Static Methods A method that is tagged as static: Can be called on the class, rather than on an object of the class (e.g., Math.sin(1.0)) Does not have an implicit parameter this Cannot directly access non-static methods or fields (because there is no this!) The Meaning of static But what does static mean? In general, static means something that belongs to the class as a whole, and not to a specific object: Static methods have no implicit parameter this Static fields belong to the whole class, shared by all objects. The Meaning of static But what does static mean? In general, static means something that belongs to the class as a whole, and not to a specific object: Static methods have no implicit parameter this Static fields belong to the whole class, shared by all objects. Huh? Java Classes When you write a class in Java, you describe what goes into each object of the class: public class UBCStudent { String name; int studentid; public String getname() { That says that each object of type UBCStudent contains a field name, and a field studentid, and the object knows how to do the getname method (applied to itself). Analogy/Intuition on static A class is a pattern/blueprint/factory that shows, by example, how to create specific types of objects: Each object has these instance fields Each object has these methods, that t do the following statements Sometimes, you want to talk about the pattern/blueprint itself, not the objects. Those are when you want to use static Real Life Analogy of static Fields A factory/blueprint for a car is like the class. The cars are the objects. The blueprint shows an engine, battery, etc. Each car gets its own engine, battery, etc. These are instance fields. But to give each car a serial number, you need a field that lives in the factory. That should be a static field. 8

UBCStudent with Automatically Assigned Student ID Numbers Each object should get a unique student ID number assigned to it. We ll keep a variable nextid that keeps track of the next available ID number. nextid is one variable for the whole class, so it should be static! Recap: Static Fields A field that is tagged as static: Is a single field of the class, rather than a separate field of each object of the class Is shared by all objects of the class Can be accessed without creating an object of the class Can be accessed from static methods Why Use static? Static methods are almost never used, with two common exceptions: Numbers aren t objects in Java, so to have a class of methods that do computation, we ll often put them in static methods (e.g., the Math class). The main method starts running before there are any objects created, so it has to be static. Why Use static? Static fields are not very common, but are needed when the class as a whole has to coordinate some information, e.g.,: Counting how many objects were created Assigning i serial numbers Having all objects share or negotiate some information in common. Recap: Variable Types Questions Static variables declared within class associated with class, not instance, indefinite lifetime Instance variables declared within class associated with instance accessible throughout object, lifetime of object Local variables declared within method accessible within method after declared, lifetime of method (to be more precise, replace method by block ) Parameters declared in parameter list of method accessible throughout method, lifetime of method 9

Midterm Info Out of 100: raw avg=56, low=1, high=97 Will be scaled (info later)! Long exam, but not unreasonable: Everyone should be able to do it (with time). Talk to friends, learning centre, WebCT, TAs, prof. See Lecture 17 notes for tips from Beth Simon Solutions will be posted. Protocol for re-mark requests: read solutions first, carefully no re-mark requests accepted until Thursday re-mark requests must be in writing (paper attached to exam) and submitted to instructor entire exam re-marked Raw Score Stats: Midterm #1 Average: 56, Low: 1, High: 97 (Out of 100) I ve made ArrayList question extra credit (3pts). Scaling Formula: Raw Score Scaled Score (raw/97) 0.7 * 100 15 27 30 44 45 58 60 71 75 84 90 95 10