Docsity

Using the Random Generator Class - Lecture Slides | CMPU 101, Study notes of Computer Science

Toggle sidebar
bg1
Chapter 6—Objects and Classes
The Art and Science of
An Introduction
to Computer Science
ERIC S. ROBERTS
Java
Objects and Classes
C H A P T E R 6
To beautify life is to give it an object.
—JosĆ© MartĆ­, On Oscar Wilde, 1888
CMPU-101
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
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
of this sort are said to be nondeterministic.
• Nondeterministic behavior is essential to many applications.
Computer games would cease to be fun if they behaved in
exactly the same way each time. Nondeterminism also has
important practical uses in simulations, in computer security,
and in algorithmic research.
Methods to Generate Random Values
The RandomGenerator class defines these non-static methods:
int nextInt(int low, int high)
Returns a random int between low and high, inclusive.
int nextInt(int n)
Returns a random int from 0 to n - 1.
double nextDouble(double low, double high)
Returns a random double d in the range low ! d < high.
double nextDouble()
Returns a random double d in the range 0 ! d < 1.
boolean nextBoolean()
Returns a random boolean value, which is true 50 percent of the time.
boolean nextBoolean(double p)
Returns a random boolean, which is true with probability p, where 0 ! p ! 1.
Color nextColor()
Returns a random color.
Using the Random Methods
• If you have an instance variable of type RandomGenerator
called rgen , you can use any of the methods shown on the
previous slide using rgen as the receiver.
• As an example, you could simulate rolling a die by calling
int die = this.rgen.nextInt(1, 6);
The 2-parameter nextInt method returns a random integer
with value 1, 2, 3, 4, 5, or 6 (i.e., 1 through 6). This method
call would return a number corresponding to one of the faces
of a 6-sided die.
Defining Your Own Classes
• The standard form of a class definition in Java looks like this:
public class name extends superclass {
class body
}
• The optional extends clause on the header line specifies the
name of the superclass. If the extends clause is missing, the
new class becomes a direct subclass of Object, which is the
root of Java’s class hierarchy.
• The body of a class consists of a collection of Java definitions
that are generically called entries. The entries include
constructors, methods, instance variables, and named
constants.
Representing Student Information
• Understanding the structure of a class is easiest in the context
of a specific example. Suppose we want to create a class
called Student, which is used to keep track of the following
information about a student:
–The name of the student
– The studen t’s six-digit identification number
– The number of credits the student has earned (which may include a
decimal fraction to account for half- and quarter-credit courses)
–A boolean indicating whether the student has paid all university fees
• Each of these values is declared in an instance variable of the
appropriate type.
• Instance variables should always be declared as private. Access
to these values is controlled by public methods exported by the
Student class.
• To distinguish instance from local variables, always use this.
when using an instance variable inside a method.
pf3
pf4
pf5

Partial preview of the text

Download Using the Random Generator Class - Lecture Slides | CMPU 101 and more Study notes Computer Science in PDF only on Docsity!

Chapter 6—Objects and Classes The Art and Science of An Introduction

ERIC S. ROBERTS^ Java^ to Computer Science

Objects and Classes

C H A P T E R 6 To beautify life is to give it an object. —JosĆ© MartĆ­, On Oscar Wilde, 1888

CMPU-

Computer Science I:

Problem-Solving and Abstraction

Fall 2008

Jennifer Walter

(adapted from slides by Eric Roberts)

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

of this sort are said to be nondeterministic.

• Nondeterministic behavior is essential to many applications.

Computer games would cease to be fun if they behaved in

exactly the same way each time. Nondeterminism also has

important practical uses in simulations, in computer security,

and in algorithmic research.

Methods to Generate Random Values

The RandomGenerator class defines these non-static methods:

int nextInt(int low, int high)

Returns a random int between low and high , inclusive.

int nextInt(int n)

Returns a random int from 0 to n - 1.

double nextDouble(double low, double high)

Returns a random double d in the range low! d < high.

double nextDouble()

Returns a random double d in the range 0! d < 1.

boolean nextBoolean()

Returns a random boolean value, which is true 50 percent of the time.

boolean nextBoolean(double p)

Returns a random boolean, which is true with probability p, where 0! p! 1.

Color nextColor()

Returns a random color.

Using the Random Methods

• If you have an instance variable of type RandomGenerator

called rgen , you can use any of the methods shown on the

previous slide using rgen as the receiver.

• As an example, you could simulate rolling a die by calling

int die = this.rgen.nextInt(1, 6);

The 2-parameter nextInt method returns a random integer

with value 1, 2, 3, 4, 5, or 6 (i.e., 1 through 6). This method

call would return a number corresponding to one of the faces

of a 6-sided die.

Defining Your Own Classes

• The standard form of a class definition in Java looks like this:

public class name extends superclass { class body }

• The optional extends clause on the header line specifies the

name of the superclass. If the extends clause is missing, the

new class becomes a direct subclass of Object, which is the

root of Java’s class hierarchy.

• The body of a class consists of a collection of Java definitions

that are generically called entries. The entries include

constructors, methods, instance variables, and named

constants.

Representing Student Information

• Understanding the structure of a class is easiest in the context

of a specific example. Suppose we want to create a class

called Student, which is used to keep track of the following

information about a student:

  • The name of the student
  • The student’s six-digit identification number
  • The number of credits the student has earned (which may include a

decimal fraction to account for half- and quarter-credit courses)

  • A boolean indicating whether the student has paid all university fees
  • Each of these values is declared in an instance variable of the

appropriate type.

  • Instance variables should always be declared as private. Access

to these values is controlled by public methods exported by the

Student class.

  • To distinguish instance from local variables, always use this.

when using an instance variable inside a method.

  • The Student class keeps track of the following pieces of data
  • about a student: the student's name, ID number, the number of
  • credits the student has earned toward graduation, and whether
  • the student is paid up with respect to university bills.
  • All of this information is entirely private to the class.
  • Clients can obtain this information only by using the various
  • methods defined by the class. / public class Student { // Note the lack of "extends" clause /* 2-parameter constructor
  • Creates a new Student object with the specified name and ID.
  • name: The student's name as a String
  • id: The student's ID number as an int */ public Student(String name, int id) { this.studentName = name; // Note that the instance this.studentID = id; // vars are not declared here }

The Student Class

This comment describes the class as a whole. The class header defines Student as a direct subclass of Object_. This comment describes the constructor. The constructor sets the instance variables. page 1 of 4 skip code_

  • The Student class keeps track of the following pieces of data
  • about a student: the student's name, ID number, the number of
  • credits the student has earned toward graduation, and whether
  • the student is paid up with respect to university bills.
  • All of this information is entirely private to the class.
  • Clients can obtain this information only by using the various
  • methods defined by the class. / public class Student { /*
  • Creates a new Student object with the specified name and ID.
  • @param name The student's name as a String
  • @param id The student's ID number as an int */ public Student(String name, int id) { studentName = name; studentID = id; }
  • Returns the name of this student / public String getName() { return this.studentName; } // end method getName /*
  • Returns the ID number of this student.

/ public int getID() { return this.studentID; } // end method getID /*

  • Sets the number of credits earned.
  • credits is the new number of credits earned */ public void setCredits(double credits) { this.credits = credits; } // end method setCredits

The Student Class

These methods retrieve the value of an instance variable and are called getters and ID number are fixed, there are. Because the student name no corresponding setters. This method changes the value of an instance variable and is called a setter. page 2 of 4 skip code /**

  • Gets the name of this student.
  • @return The name of this student / public String getName() { return studentName; } /*
  • Gets the ID number of this student.
  • @return The ID number of this student / public int getID() { return studentID; } /*
  • Sets the number of credits earned.
  • @param credits The new number of credits earned */ public void setCredits(double credits) { creditsEarned = credits; }
  • Returns the number of credits earned by this student.

/ public double getCredits() { return this.credits; } // end method getCredits /*

  • Sets whether the student is paid up.
  • flag: The value true or false indicating paid-up status / public void setPaidUp(boolean flag) { this.paidUp = flag; } // end method setPaidUp /*
  • Returns whether the student is paid up. */ public boolean isPaidUp() { return this.paidUp; } // end method isPaidUp

The Student Class

Names for getter methods usually begin with the prefix get_. The only exception is for getter methods that return a_ boolean , in which case the name typically begins with is_. page 3 of 4 skip code_

  • Gets the number of credits earned.
  • @return The number of credits this student has earned / public double getCredits() { return creditsEarned; } /*
  • Sets whether the student is paid up.
  • @param flag The value true or false indicating paid-up status / public void setPaidUp(boolean flag) { paidUp = flag; } /*
  • Returns whether the student is paid up.
  • @return Whether the student is paid up */ public boolean isPaidUp() { return paidUp; }
  • Creates a string identifying this student.
  • Return the string used to display this student / public String toString() { return this.studentName + " (#" + this.studentID + ")"; } / Public constants / /* The number of credits required for graduation / public static final double CREDITS_TO_GRADUATE = 34.0; / Private instance variables / private String studentName; / The student's name / private int studentID; / The student's ID number / private double credits = 0; / number of credits earned / private boolean paidUp = false;/ Is student is paid up? */ } // end class Student

The Student Class

The tells Java how to display toString method a value of this class. All of your classes should override toString_. Classes often export named constants. These declarations define the instance variables that maintain the internal state of the class. All instance variables used in the text are private. page 4 of 4 skip code_

Using the Student Class

• Once you have defined the Student class, you can then use

its constructor to create instances of that class. For example,

you could use the following code to declare and instantiate

two Student objects with variable names shown:

Student chosenOne = new Student("Harry Potter", 123456); Student topStudent = new Student("Hermione Granger", 314159);

• You can then use the standard receiver syntax to call methods

on these objects. For example, you could set Hermione’s

number-of-credits field to 97 by writing

or get Harry’s full name by calling

topStudent.setCredits(97); chosenOne.getName();

Exercise: Design an Employee Class

• Create a definition for a class called Employee, which keeps

track of the following information:

  • The name of the employee
  • A number indicating the order in which this employee was hired
  • A flag indicating whether the employee is still active
  • The salary (a number that may contain a decimal fraction)

• The name and employee number should be assigned as part of

the constructor call, and it should not be possible to change

them subsequently. By default, new employees should be

marked as active. The salary field need not be initialized.

• The class should export appropriately named getters for all

four fields and setters for the last two.

Rules for Inherited Methods

• When one class extends another, the subclass is allowed to

override method definitions in its superclass. Whenever you

invoke that method on an instance of the extended class, Java

chooses the new version of the method provided by that class

and not the original version provided by the superclass.

• The decision about which version of a method to use is

always made on the basis of what the object in fact is and not

on what it happens to be declared as at that point in the code.

Writing Graphics Programs

that Respond to Mouse Events

• Graphics applications often make it possible for the user to

control the action of a program by using an input device such

as a mouse. Programs that support user control are called

interactive programs (aka, Graphical User Interfaces or

GUIs).

• User actions such as clicking the mouse are called events.

Programs that respond to events are said to be event-driven.

• When you write an event-driven program, you indicate the

events to which you wish to respond by adding a listener for

that event. When the event occurs, a message is sent to the

listener, triggering a response. Each response must be coded

in a separate method with a particular signature and you must

write the code in the body of each method.

The Role of Event Listeners

• One way to visualize the role of a listener is to imagine that

you have access to one of Fred and George Weasley’s

ā€œExtendable Earsā€ from the Harry Potter series.

ListenerExample

Methods that Respond to Mouse Events

• To write a graphics program that responds to Mouse events,

you should include the line

this.addMouseListener();

in the constructor.

• After including this line, your program can include the

following void methods to respond to mouse clicks, mouse

releases, and other mouse events.

mouseClicked( e ) mousePressed( e ) mouseReleased( e ) mouseMoved( e ) mouseDragged( e ) Called when the user clicks the mouse Called when the mouse button is pressed Called when the mouse button is released Called when the user moves the mouse Called when the mouse is dragged with the button down

A Simple Event-driven Program

The easiest way to illustrate event handling is by example. The

following program listens for mouse clicks and simulates the sun

rising over the edge of the graphics window, going higher with

each click.

/** Raises a GOval, the sun / public class Sunrise extends GraphicsProgram { public GOval sun; public Sunrise() { this.start(); sun = new GOval(this.getWidth()/2 - 100, this.getHeight(), 200,200); sun.setFilled(true); sun.setColor(Color.YELLOW); this.add(sun); this.addMouseListeners(); } / executed when mouse button is clicked */ public void mouseClicked(MouseEvent e) { sun.move(0,-5); } }

A Simple Event-driven Program

When the user clicks the mouse, Java responds by invoking the

mouseClicked method in the listener. The argument e is a

MouseEvent object that describes the event.

/** Raises a GOval, the sun / public class Sunrise extends GraphicsProgram { public GOval sun; public Sunrise() { this.start(); sun = new GOval(this.getWidth()/2 - 100, this.getHeight(), 200,200); sun.setFilled(true); sun.setColor(Color.YELLOW); this.add(sun); this.addMouseListeners(); } / executed when mouse button is clicked */ public void mouseClicked(MouseEvent e) { sun.move(0,-5); } }

A Simple Event-driven Program

The definitions for the standard event and listener classes are in

the java.awt.event package, which means that you need to

import this package in interactive programs.

/** Raises a GOval, the sun / public class Sunrise extends GraphicsProgram { public GOval sun; public Sunrise() { this.start(); sun = new GOval(this.getWidth()/2 - 100, this.getHeight(), 200,200); sun.setFilled(true); sun.setColor(Color.YELLOW); this.add(sun); this.addMouseListeners(); } / executed when mouse button is clicked */ public void mouseClicked(MouseEvent e) { sun.move(0,-5); } }

Graphics Interlude

• Using images in your programs.

Suppose we want to do more than just draw our own objects

in a GraphicsProgram. It is very simple to insert digitized

images into your programs.

The GImage class is used to constuct images on the canvas.

Suppose I had the following image that I wanted to place on

the canvas.

Using the GImage class

• Use the following lines to declare and add the GImage shown

on the last slide, called "HappySun.jpg", to a graphics

program:

private GImage sun;

sun = new GImage("HappySun.jpg",100,100);

The GImage class

• Files that can be used as images have either a .jpg or .gif

extension

• The image file should be in the same directory (ie, folder) as

any Java program that uses the image.

• Methods that can be called on a GImage can be found in the

acm library documentation (ie, the ACM Java API).

import acm.program.; import acm.graphics.; import java.awt.event.; /*

  • This class raises a cool sun as the mouse is clicked / public class SunriseImage extends GraphicsProgram { / instance variable for sun / public GImage sun; / named constant for diameter of sun / public static final int SUN_SIZE = 400; / named constant for move increments */ public static final int MOVE_UP = -10;

The SunriseImage Class

page 1 of 2 /* 0-parameter constructor / public SunriseImage() { this.start(); / Create sun in its initial position / this.sun = new GImage("HappySun.jpg"); this.sun.setBounds(this.getWidth()/2 - SUN_SIZE/2, this.getHeight(), SUN_SIZE, SUN_SIZE); this.add(sun); / Add the mouse listener / this.addMouseListeners(); } / Each mouse click causes the GImage sun to move up */ public void mouseClicked(MouseEvent e) { sun.move(0,MOVE_UP); } }

The SunriseImage Class

page 2 of 2