Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

Similar documents
Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

COMP 110 Programming Exercise: Simulation of the Game of Craps

Chapter 4: Writing Classes

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

Function Call Stack and Activation Records

Chapter 4 Defining Classes I

Programming Lecture 6

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Anatomy of a Class Encapsulation Anatomy of a Method

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

C Functions. 5.2 Program Modules in C

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Lecture 7. Random number generation More randomized data structures Skip lists: ideas and implementation Skip list time costs

CS 116 Week 8 Page 1

Functions and Recursion

EECS168 Exam 3 Review

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

CS 251 Intermediate Programming Methods and More

CPSC 427: Object-Oriented Programming

Lecture 04 FUNCTIONS AND ARRAYS

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

PROGRAMMING LANGUAGE 2

Lecture 5: Methods CS2301

IT 374 C# and Applications/ IT695 C# Data Structures


Use the scantron sheet to enter the answer to questions (pages 1-6)

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CO Java SE 8: Fundamentals

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

CS 251 Intermediate Programming Methods and Classes

CSC 1351: Quiz 6: Sort and Search

Introduction to Programming Using Java (98-388)

Creating Java Programs with Greenfoot

Objects and Classes -- Introduction

CS1004: Intro to CS in Java, Spring 2005

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Objects, Subclassing, Subtyping, and Inheritance

Building Java Programs

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

The Notion of a Class and Some Other Key Ideas (contd.) Questions:

CSE123. Program Design and Modular Programming Functions 1-1

CS61B Lecture #32. Last modified: Sun Nov 5 19:32: CS61B: Lecture #32 1

Static Methods. Why use methods?

CPSC 427: Object-Oriented Programming

ITI Introduction to Computing II

1 Short Answer (15 Points Each)

ECE 122. Engineering Problem Solving with Java

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

ECE 122. Engineering Problem Solving with Java

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS 10, Fall 2015, Professor Prasad Jayanti

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

ITI Introduction to Computing II

Chapter 1 Getting Started

Chapter 4 Classes in the Java Class Libraries

Chapter 6 Introduction to Defining Classes

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Java Outline (Upto Exam 2)

9/10/2018 Programming Data Structures Inheritance

Programming Exercise 14: Inheritance and Polymorphism

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Software Design and Analysis for Engineers

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

More About Objects and Methods

Basics of Programming with Python

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

LAB 13: ARRAYS (ONE DIMINSION)

Chapter 5 Object-Oriented Programming

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Programming Assignment #4 Arrays and Pointers

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

CSCE3193: Programming Paradigms

Aggregation. Introduction to Computer Science I. Overview (1): Overview (2): CSE 1020 Summer Bill Kapralos. Bill Kapralos.

Class, Variable, Constructor, Object, Method Questions

ENCAPSULATION. private, public, scope and visibility rules. packages and package level access.

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Logistics. Final Exam on Friday at 3pm in CHEM 102

More about Loops and Decisions

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Instance Members and Static Members

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

CS 139 Practice Midterm Questions #2

CS1150 Principles of Computer Science Methods

Chapter 5: Writing Classes and Enums

Building Java Programs

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

University of Massachusetts Amherst, Electrical and Computer Engineering

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

OBJECT ORIENTED SIMULATION LANGUAGE. OOSimL Reference Manual - Part 1

Assignment 1 due Monday at 11:59pm

Transcription:

Spring 2014

Student Responsibilities Reading: Textbook, Sections 6.1 6.3 Attendance

Recall: Writing Methods Decomposition: break a problem down into smaller subproblems Use methods whenever you can in labs from now on. scope type name (argument list) { statements in the method body } 1. scope indicates who has access to the method (public) 2. type indicates what type of value the method returns 3. name is the name of the method 4. argument list is the list of declarations for the variables used to hold the values of each argument

Notes About Using Methods A method invocation or call uses its name and supplies arguments that correspond to the parameters in the method implementation. A predicate method returns a boolean value. You must be aware of the return type of any method you invoke, since you will either be: using it in an expression assigning it to an object or displaying it if(!ispalindrome(n)) -or- double x = sqrt(y) Do not place a print or println statement in a method to display a calculated value unless that is the express purpose of the method. If the return type isn t void, the method shouldn t display any results.

Chapter Six: Before writing our own classes, it helps to look more closely at how to use classes that someone else has developed. Using the Generator Class The Generator class makes it possible to write programs that simulate random processes, such as flipping a coin or rolling a die. Programs that involve random processes like this are said to be non deterministic. Non determinism is essential to many applications, such as computer games. It also has important practical uses in simulations, computer security, and algorithmic research.

Creating a Generator Object The first step in writing a program that uses randomness is to create an instance (object) of the Generator class. The best way to do so, is to call the getinstance() method, which returns a single shared instance of a random generator. The standard for that declaration looks like this: private Generator rgen = Generator.getInstance();

This declaration usually appears outside of any method (but still in the program class), and is therefore an example of an instance variable. The keyword private indicates that this variable can be used from any method within this class, but is not accessible to other classes. To obtain a random value, send a message to the generator (rgen in the last example), which responds with the result.

Generator Method Interfaces public int nextint(int low, int high) Returns a random int in interval [low..high] public int nextint(int n) Returns a random int in interval [0..n 1] public double nextdouble(double low, double high) Returns a random double d, low d <high public double nextdouble() Returns a random double d, 0 d < 1 public boolean nextboolean() Returns a random boolean, which is true 50% of the time public boolean nextboolean(double p) Returns a random boolean, which is true with probability p, 0 p < 1 public Color nextcolor() Returns a random color

Using Generator Methods To use Generator methods, invoke them using the name of your Generator instance (e.g., rgen) as the receiver. As an example, you could simulate rolling a die by: int die = rgen.nextint(1, 6); To simulate flipping a coin: boolean isheads = rgen.nextboolean();

Notes on Methods The nextint(), nextdouble(), and nextboolean() methods all exist in more than one form. Java determines which version is used by checking the number and types of arguments used. Methods that have the same name but differ in their argument structure are said to be overloaded.

Examples: Generating Values To set the variable total to the sum of two six sided dice: int d1 = rgen.nextint(1, 6); int d2 = rgen.nextint(1, 6); int total = d1 + d2; To flip a coin that comes up heads 60% of the time: boolean isheads = rgen.nextboolean(0.6); To randomly change the fill color of rect: rect.setfillcolor(rgen.nextcolor());

The Dice Game At the beginning of the game, the player rolls a pair of dice and computes the total. 1. If the total is 2, 3, or 12 (called craps ), the player loses, game over. 2. If the total is 7 or 11 (called a natural ), the player wins, game over. 3. If the total is any other number (4, 5, 6, 8, 9, or 10), that number becomes the point. From here, the player keeps rolling the dice until: 3.1 the point comes up again, in which case the player wins or 3.2 a 7 appears, in which case the player loses. (The numbers 2, 3, 11, and 12 have no special significance after the first roll.)

Algorithm Roll two dice, yielding total If total is 7 or 11 player automatically wins otherwise if total is 2, 3, or 12 player automatically loses otherwise (player has rolled 4, 5, 6, 8, 9, or 10, their point) player continues to roll dice until they roll their point and win, or they roll a 7 and lose

Simulating rolltwodice() /* Rolls two dice and returns their sum. */ private int rolltwodice() { int d1 = rgen.nextint(1, 6); int d2 = rgen.nextint(1, 6); return d1 + d2; } /* Private instance variables / private Generator rgen = Generator.getInstance(); Warning: do not use print() or println() in a method unless that is the method s purpose.

The Program public void run() { int total = rolltwodice(); switch (total) { case 7: case 11: println("you rolled a natural. You win."); break; case 2: case 3: case 12: println("you rolled " + total + ". You lose."); break;

default: // rolled 4, 5, 6, 8, 9, or 10 int point = total; println("your point is: " + point + "."); total = rolltwodice(); while (total!= 7 && total!= point){ println("you rolled " + total + ", rolling again."); total = rolltwodice(); } // end while if (total == point) println("you made your point. You win."); else // (total == 7) println("you rolled a 7. You lose."); } // end switch } // end run()

and Implementers It is useful to recognize that there are two perspectives that we can take with respect to a particular class. Often, we will find ourselves using a class we didn t write (for example, the Generator class). When this happens, we are acting as a client of the class. When we write the code for a method, we are acting as an implementer. and Implementers look at a class in different ways.

Two Views of Methods need to know: what methods are available in a class, and how to call them are not interested in the details of how a method works. The Implementer, on the other hand, is primarily interested in precisely those details. The Implementer of a class should try to hide complexity from its clients. The Generator class hides a considerable amount of complexity.

Layered Abstractions The Generator class is actually implemented as a subclass of a class called. Some of the methods we call to produce random values are defined in the Generator class itself; others are inherited from the class. A client does not need to know which is which. Class hierarchies that define methods at different levels are called layered abstractions.

Java Every Java class is part of a package, which is a collection of related classes that have been released as a coherent unit. The Generator class is defined in a package called acm.util, which is part of the ACM Java Libraries. The class is part of the java.util package, which is a collection of general utility classes. Whenever we refer directly to a class, we should import the package in which it lives.

Importing For example, any program using the Generator class should include the line: import acm.util.*; When we use the Generator class, we do not need to import the java.util package (unless it is used for some other purpose), since that is taken care of in acm.util. The fact that Generator is built on top of is part of the complexity hidden from clients.

is Difficult Non deterministic behavior turns out to be difficult to achieve on a computer. A computer executes its instructions in a precise, predictable way. If you give a computer program the same inputs, it will generate the same outputs every time. This is not what we want in a non deterministic program.

Simulating Given that true non determinism is so difficult to achieve in a computer, classes such as Generator must instead simulate randomness by carrying out a deterministic process that satisfies the following criteria: 1. The values generated by that process should be difficult for human observers to predict. 2. Those values should appear to be random, in the sense that they should pass statistical tests for randomness. Because the process is not truly random, the values generated by Generator instances are said to be pseudo random

Pseudo random Numbers The Generator class uses a mathematical process to generate a series of integers that appear to be random. The code that implements this process is called a pseudo random number generator. The best way to visualize a pseudo random number generator is to think of it as a black box that generates a sequence of values, even though the details of how it does so are hidden. Give me the next pseudo random number 155629808 pseudo random number generator instance

Black Box Operation To obtain the next pseudo random number, we send a message to the generator asking for the next number in its sequence. The generator then responds by returning that value. Repeating these steps generates a new value each time.

The Number The pseudo random number generator used by the and Generator classes generates seemingly random values by applying a function to the previous result. The seed is the starting point for this sequence of values. As part of the process of starting a program, Java initializes the seed for its pseudo random number generator to a value based on the system clock, which changes very quickly on a human time scale. Programs executed just a few milliseconds apart will therefore get a different sequence of random values.

Not so random Numbers Computers, however, run much faster than the internal clock can register. If we create two Generator instances in a single program, it is likely that both will be initialized to the same seed, and therefore, generate exactly the same sequence of values. This fact explains why it is important to create only one Generator instance (like rgen) in an application.

Debugging and Behavior Even though unpredictable behavior is essential for programs like computer games, such unpredictability often makes debugging extremely difficult. Because the program runs in a different way each time, there is no way to ensure that a bug that turns up the first time we run a program will happen again the second time around. To get around this problem, it is often useful to have our programs run deterministically during the debugging phase.

Setting the To accomplish this, we can use the set() method: rgen.set(1); This call sets the random number seed so that the internal random number sequence will begin at the same point every time the program is executed. The value 1 is arbitrary changing this value will change the sequence, but whatever that sequence is, it will be the same on each run.

Chaos Game

Suppose we wish to work our way from one end of an interval to the other end, using equal steps... We will begin with the smallest value in the interval.

Two Points on an Interval DeltaX = (b a)/1 a b a+deltax If we use two points, DeltaX is the entire interval.

Three Points on an Interval DeltaX = (b a)/2 a a+deltax b a+2deltax If we use three points, DeltaX is half the entire interval.

Four Points on an Interval DeltaX=(b a)/3 a a+deltax a+2deltax b a+3deltax If we use four points, DeltaX is one third the entire interval.

Sine & Cosine Curves

Defining Our Own The standard form of a class definition in Java: public class name extends superclass { class body } The extends clause on the header line specifies the name of the superclass, from which this class is derived. If the extends clause is missing, the new class becomes a direct subclass of Object, which is the root of Java s class hierarchy.

Class Contents The body of a class consists of a collection of Java definitions that are generically called entries. The most common entries are: 1. constructors how to create an instance (how to initialize an object of the class) 2. methods the methods associated with the class 3. instance variables any necessary local objects 4. named constants any necessary constants for the class

Controlling Access to Entries Each entry in a Java class is marked with a keyword to control which classes have access to (can see ) that entry. The types of access are termed public, private, and protected. The text uses only public and private. All entries are marked as private unless there is a compelling reason to export them.

Access Privileges public private protected (no keyword) All classes in the program have access; public entries in a class are said to be exported by that class. Access is limited to the class itself, making that entry completely invisible outside the class. Access is restricted to the class that defines these entities, along with any of its subclasses or any classes in the same package. The entry is visible only to classes in the same package, and is called package private.