Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Mat 2170 Review Week 9 Random Overloading Craps Objects and - - PowerPoint PPT Presentation
Mat 2170 Review Week 9 Random Overloading Craps Objects and - - PowerPoint PPT Presentation
Mat 2170 Week 9 Objects and Classes Week 9 Mat 2170 Review Week 9 Random Overloading Craps Objects and Classes Clients Packages Randomness Seed Spring 2014 Lab 9 Intervals Classes Student Responsibilities Mat 2170 Week 9
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Student Responsibilities
Reading: Textbook, Sections 6.1 – 6.3 Lab 9 Attendance
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
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
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
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
- r 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
- f the method. If the return type isn’t void, the method
shouldn’t display any results.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Chapter Six: Objects and Classes
Before writing our own classes, it helps to look more closely at how to use classes that someone else has developed.
Using the RandomGenerator Class
The RandomGenerator 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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Creating a RandomGenerator Object
The first step in writing a program that uses randomness is to create an instance (object) of the RandomGenerator 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 RandomGenerator rgen = RandomGenerator.getInstance();
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
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
- ther classes.
To obtain a random value, send a message to the generator (rgen in the last example), which responds with the result.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
RandomGenerator 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
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Using RandomGenerator Methods
To use RandomGenerator methods, invoke them using the name of your RandomGenerator 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();
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Notes on Overloading 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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Examples: Generating Random 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());
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
The Dice Game ”Craps”
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.)
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Craps Algorithm
Roll two dice, yielding total If total is 7 or 11 player automatically wins
- therwise if total is 2, 3, or 12
player automatically loses
- therwise
(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
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Simulating Craps – 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 RandomGenerator rgen = RandomGenerator.getInstance(); Warning: do not use print() or println() in a method unless that is the method’s purpose.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
The Craps 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;
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
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()
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Clients 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 RandomGenerator 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. Clients and Implementers look at a class in different ways.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Two Views of Methods
Clients need to know:
what methods are available in a class, and how to call them
Clients 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 RandomGenerator class hides a considerable amount of complexity.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Layered Abstractions
The RandomGenerator class is actually implemented as a subclass of a class called Random. Some of the methods we call to produce random values are defined in the RandomGenerator class itself; others are inherited from the Random class. A client does not need to know which is which. Class hierarchies that define methods at different levels are called layered abstractions.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Java Packages
Every Java class is part of a package, which is a collection
- f related classes that have been released as a coherent
unit. The RandomGenerator class is defined in a package called acm.util, which is part of the ACM Java Libraries. The Random 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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Importing Packages
For example, any program using the RandomGenerator class should include the line: import acm.util.*; When we use the RandomGenerator class, we do not need to import the java.util package (unless it is used for some
- ther purpose), since that is taken care of in acm.util.
The fact that RandomGenerator is built on top of Random is part of the complexity hidden from clients.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Randomness 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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Simulating Randomness
Given that true non–determinism is so difficult to achieve in a computer, classes such as RandomGenerator 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 RandomGenerator instances are said to be pseudo–random
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Pseudo–random Numbers
The RandomGenerator 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.
155629808
Give me the next pseudo−random number
generator instance pseudo−random number
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
The Random Number Seed
The pseudo–random number generator used by the Random and RandomGenerator 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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Not–so–random Numbers
Computers, however, run much faster than the internal clock can register. If we create two RandomGenerator instances in a single program, it is likely that both will be initialized to the same seed, and therefore, generate exactly the same sequence
- f values.
This fact explains why it is important to create only one RandomGenerator instance (like rgen) in an application.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Debugging and Random 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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Setting the Seed
To accomplish this, we can use the setSeed() method: rgen.setSeed(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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Chaos Game
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Intervals
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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Two Points on an Interval
(b−a)/1
DeltaX =
b a a+DeltaX
If we use two points, DeltaX is the entire interval.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Three Points on an Interval b a
a+DeltaX a+2DeltaX DeltaX = (b−a)/2 If we use three points, DeltaX is half the entire interval .
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Four Points on an Interval b a
a+3DeltaX a+2DeltaX a+DeltaX DeltaX=(b−a)/3
If we use four points, DeltaX is one–third the entire interval.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Sine & Cosine Curves
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
Defining Our Own Classes
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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
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
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes
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.
Mat 2170 Week 9 Objects and Classes Week 9 Review Random Overloading Craps Clients Packages Randomness Seed Lab 9 Intervals Classes