object-oriented programming 95-712 mism/msit carnegie mellon university lecture 2: program control

50
Object-Oriented Object-Oriented Programming Programming 95-712 95-712 MISM/MSIT MISM/MSIT Carnegie Mellon Carnegie Mellon University University Lecture 2: Program Lecture 2: Program Control Control

Post on 19-Dec-2015

217 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Object-Oriented ProgrammingObject-Oriented Programming95-71295-712

MISM/MSITMISM/MSIT

Carnegie Mellon UniversityCarnegie Mellon University

Lecture 2: Program ControlLecture 2: Program Control

Page 2: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Today We Look AtToday We Look At

Java operatorsJava operators Control structuresControl structures More example programsMore example programs

Page 3: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Java OperatorsJava Operators

An operator takes one or more “things” and An operator takes one or more “things” and produces a resultant “thing”.produces a resultant “thing”.

““Things” are usually primitive types, but Things” are usually primitive types, but they are sometimes objects.they are sometimes objects.

The “things” operated upon are called The “things” operated upon are called operands.operands.

An operator is just a function, but with a An operator is just a function, but with a different syntax.different syntax.

Page 4: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

A Familiar ExampleA Familiar Example

The assignment operator and the addition The assignment operator and the addition operator are used (each exactly once!).operator are used (each exactly once!).

This is a more familiar syntax than, e.g.,This is a more familiar syntax than, e.g.,k.equals(i.add(j));k.equals(i.add(j));

int i = 3, j = 4, k;k = i + j;

Page 5: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

More Operator FactsMore Operator Facts

All operators produce a value.All operators produce a value. Sometimes they produce side effects, i.e., Sometimes they produce side effects, i.e.,

they change the value of an operand.they change the value of an operand. Evaluation of a statement with several Evaluation of a statement with several

operators follows precedence rules. Use operators follows precedence rules. Use parentheses for readability.parentheses for readability.

(x + y) * z / 3(x + y) * z / 3 is different than is different than x + y * z / 3x + y * z / 3

Page 6: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Assignment Is Tricky, Part IAssignment Is Tricky, Part Ipublic class Number { int i;}public class Assignment1 { public static void main(String[] args) { Number n1 = new Number(); Number n1 = new Number(); n1.i = 2; n2.i = 5; n1.i = n2.i; n2.i = 10; // what is n1.i? }}

Page 7: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Assignment Is Tricky, Part IIAssignment Is Tricky, Part IIpublic class Assignment2 { public static void main(String[] args) { Number n1 = new Number(); Number n1 = new Number(); n1.i = 2; n2.i = 5; n1 = n2; n2.i = 10; // what is n1.i? n1.i = 20; // what is n2.i? }}

Page 8: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

A Picture Might HelpA Picture Might Help

n1 n2

reference variables Number objects

n2.i n1.i

Before assignment n1 = n2

n1 n2

reference variables Number objects

n2.i n1.i

After assignment n1 = n2

5 2

5 2

Page 9: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

““Aliasing” In Function CallsAliasing” In Function Callspublic class PassObject { static void f(Number m) { m.i = 15; } public static void main(String[] args) { Number n = new Number(); f(n); // what is n.i now? }}

Page 10: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Math OperatorsMath Operators

+, -, *, /, %+, -, *, /, % Integer division truncates, i.e., 16/3 = 5Integer division truncates, i.e., 16/3 = 5 Modulus operator returns remainder on integer Modulus operator returns remainder on integer

division, i.e., 16%3 = 1division, i.e., 16%3 = 1 Shorthand:Shorthand:

x += 4;x += 4; is the same asis the same as

x = x + 4;x = x + 4;

This works for the other math operators as well.This works for the other math operators as well.

Page 11: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Auto Increment and DecrementAuto Increment and Decrement

++ increases by one, and -- decreases by ++ increases by one, and -- decreases by one.one.

Two flavors of each: pre and post:Two flavors of each: pre and post:

int i = 1, j;

j = i++; // j = 1, i = 2j = ++i; // j = 3, i = 3j = i--; // j = 3, i = 2j = --i; // j = 1, i = 1

Page 12: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Booleans and Relational OperatorsBooleans and Relational Operators

The The booleanboolean type has two possible values, type has two possible values, truetrue and and falsefalse..

The relational operators The relational operators >>, , >=>=, , <<, , <=<=, , ==== and and !=!= produce a produce a booleanboolean result. result.

>>, , >=>=, , <<, , <= <= are legal for all built-in types are legal for all built-in types except except booleanbooleans, s, ==== and and !=!= are legal for all. are legal for all.

Page 13: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Testing for (Non-)EquivalenceTesting for (Non-)Equivalence

The The ==== and and !=!= operators need to be used operators need to be used with care with objects.with care with objects.

public class Equivalence { public static void main(String[] args) { Integer n1 = new Integer(47); Integer n2 = new Integer(47); System.out.println(n1 == n2); // prints false System.put.println(n1 != n2); // prints true }}

Page 14: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The The equals( )equals( ) Operator Operator

This exists for all This exists for all objectsobjects (don’t need it for (don’t need it for built-in types).built-in types).

Integer n1 = new Integer(47);Integer n2 = new Integer(47);System.out.println(n1.equals(n2); // prints true

Page 15: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The The equals( )equals( ) Operator (cont.) Operator (cont.)

But But existsexists doesn’t necessarily mean doesn’t necessarily mean properly defined!properly defined!

class Number { int i;}:Number n1 = new Number();Number n2 = new Number();n1.i = 3;n2.i = 3;System.out.println(n1.equals(n2)); // prints false

Page 16: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The The equals( )equals( ) Operator (cont.) Operator (cont.)

The The equals( )equals( ) operator is properly defined operator is properly defined for most Java library classes.for most Java library classes.

The default behavior is to compare The default behavior is to compare references, so…references, so…

When you define a class, if you’re planning When you define a class, if you’re planning to use to use equals( )equals( ), you need to define it (i.e., , you need to define it (i.e., override the default behavior).override the default behavior).

Page 17: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Logical OperatorsLogical Operators

These are AND (These are AND (&&&&), OR (), OR (||||), and NOT ), and NOT ((!!).).

These work on These work on booleanbooleans only; if you have s only; if you have old “C” habits, forget them!old “C” habits, forget them!

Use parentheses freely to group logical Use parentheses freely to group logical expressions.expressions.

Logical expressions Logical expressions short-circuitshort-circuit; as soon ; as soon as the result is known, evaluation stops.as the result is known, evaluation stops.

Page 18: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Short-Circuiting ExampleShort-Circuiting Example

public class ShortCircuit { static boolean test1(int val) {return val < 1;} static boolean test2(int val) {return val < 2;} static boolean test3(int val) {return val < 3;} public static void main(String[] args) { if (test1(0) && test2(2) && test3(2)) System.out.println(“Expression is true”); else System.out.println(“Expression is false”); }}

Page 19: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Bitwise, Shift, Ternary OperatorsBitwise, Shift, Ternary Operators

Bitwise & shift operators manipulate Bitwise & shift operators manipulate individual bits in integral primitive types.individual bits in integral primitive types.

I almost never use them, except for masks, I almost never use them, except for masks, when memory is tight. YMMVwhen memory is tight. YMMV

The ternary if-else operator looks like this:The ternary if-else operator looks like this:

The result is either The result is either value0value0 or or value1value1, , depending on the truth of the depending on the truth of the booleanboolean..

boolean-expression ? value0 : value1

Page 20: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

TheThe String + String + Operator Operator

The The ++ operator is “overloaded” for operator is “overloaded” for StringString objects; it means concatenation.objects; it means concatenation.

It reminds me of good old C++…It reminds me of good old C++… If an expression begins with a If an expression begins with a StringString, then , then

all the following operands of all the following operands of ++ will be will be converted into Strings:converted into Strings:int x = 0, y = 1; z = 2;String myString = “x, y, z ”;System.out.println(myString + x + y + z);

Page 21: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

CastingCasting

A cast produces a temporary new value of a A cast produces a temporary new value of a designated type.designated type.

Implicit and explicit casts:Implicit and explicit casts:

int i = 2;float f = i; // OK, since f can hold all of ifloat g = 3.14159;//! int j = g; // not OK, loses informationint k = (int) g; // OK, compiler is reassured

Page 22: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Execution Control: iExecution Control: if-elsef-else

if (boolean_expression) statementelse if(boolean_expression) statement:else if(boolean_expression) statementelse statement

Page 23: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

if-elseif-else Example Example

public int test(int testVal, int target) { int result = 0; if (testVal > target) result = +1; else if (testVal < target) result = -1; else { System.out.println(“They are equal”); result = 0; } return result;}

Page 24: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Execution Control: Execution Control: returnreturn

Exit a method, returning an actual value or Exit a method, returning an actual value or object, or not (if the return type is void).object, or not (if the return type is void).public int test(int testVal, int target) {if (testVal > target) return = +1; else if (testVal < target) return = -1; else { System.out.println(“They are equal”); result = 0; }}

Page 25: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Three Kinds of IterationThree Kinds of Iterationwhile (boolean_expression) // evaluate first statement_or_block

do statement_or_block // evaluate lastwhile (boolean_expression)

for (initialization ; boolean_expression ; step) statement_or_block

Example:for (int i = 0; i < myArray.size(); i++) { myArray[i] = 0;}

Page 26: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

public class BreakAndContinue { public static void main(String[] args) { for (int i = 0; i < 100; i++) { if (i == 74) break; // out of for loop if (i % 9 != 0) continue; // next iteration System.out.println(i); } int i = 0; // this does work while (true) { // an infinite loop i++; int j = i * 27; if (j == 1269) break; // out of loop if (i % 10 != 0) continue; // top of loop } }}

Page 27: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Selection Via Selection Via switchswitchfor (int i = 0; i < 100; i++) { char c = (char) (Math.random() * 26 + ‘a’); switch(c) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: System.out.println(“Vowel”); break; case ‘y’: case ‘w’: System.out.println(“Sometimes a vowel”); break; default: System.out.println(“Not a vowel”);}

Page 28: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Digression on Random NumbersDigression on Random Numbers

Despite theory, most random number generators Despite theory, most random number generators are more like “kids playing with matches”. are more like “kids playing with matches”. – See “Random Number Generators: Good Ones Are Hard See “Random Number Generators: Good Ones Are Hard

to Find” by S. Park and K. Miller, to Find” by S. Park and K. Miller, CACMCACM Oct. 1988. Oct. 1988. Most random number generators use Most random number generators use

“multiplicative linear congruential” schemes: “multiplicative linear congruential” schemes: – A modulus A modulus mm, a large prime integer, a large prime integer– A multiplier A multiplier aa, an integer in the range 2,3,…m-1, an integer in the range 2,3,…m-1– These produce a sequence zThese produce a sequence z11, z, z22, z, z33… using the iterative … using the iterative

equation equation – zzi+1i+1 = f(z = f(zii) = a*z % m ) = a*z % m

Page 29: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Random Numbers (cont.)Random Numbers (cont.)

The sequence is initiated by choosing a seed. The sequence is initiated by choosing a seed. Example: f(z) = 6z %13. This produces the Example: f(z) = 6z %13. This produces the

sequence ...1 , 6, 10, 8, 9, 2, 12, 7, 3, 5, 4, 11, 1,... sequence ...1 , 6, 10, 8, 9, 2, 12, 7, 3, 5, 4, 11, 1,... Example: f(z) = 7z % 13. This produces the Example: f(z) = 7z % 13. This produces the

sequence ...1 , 7, 10, 5, 9, 11, 12, 6, 3, 8, 4, 2, 1,... sequence ...1 , 7, 10, 5, 9, 11, 12, 6, 3, 8, 4, 2, 1,... Is the latter somehow "less random"? Is the latter somehow "less random"? Example: f(z) = 5z %13. This produces the Example: f(z) = 5z %13. This produces the

sequence ...1 , 5, 12, 8, 1... sequence ...1 , 5, 12, 8, 1...

Page 30: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Examples of Rotten RNGsExamples of Rotten RNGs

IBM's RANDU for SYSTEM/360: IBM's RANDU for SYSTEM/360: – f(z) = 65539z % 2f(z) = 65539z % 23131. Not full period, dependent on results . Not full period, dependent on results

of overflow operations, low-order bits cycle w/ period 2! of overflow operations, low-order bits cycle w/ period 2! Prime’s Scheffield Pascal, an even worse version Prime’s Scheffield Pascal, an even worse version SAS SAS Modula 2 Modula 2 Many LISPs and Prologs Many LISPs and Prologs Hundreds of CS textbooks Hundreds of CS textbooks Turbo Pascal Turbo Pascal One generator had a fixed point! One generator had a fixed point!

Page 31: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Using Java’s RNGs (cont.)Using Java’s RNGs (cont.)

java.lang.Mathjava.lang.Math– static double random()static double random() random in [0, 1.0)random in [0, 1.0)

The sequence doesn’t seem to be repeatableThe sequence doesn’t seem to be repeatable Bad for debuggingBad for debugging Good for experimental workGood for experimental work

Page 32: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

What’s a Seed?What’s a Seed?

Random number sequence

-1321140701

1591074477

646222811

1633627825

-2039264851

-315534709

Here is a sequence I generated on Friday at 9:30, with the code:Random randomGenerator = new Random(); for (int i = 0; i < 10; i++) System.out.println(randomGenerator.nextInt());

i = 0i = 1

i = 2

i = 3

i = 4i = 5

Page 33: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

What’s a Seed?What’s a Seed?

Random number sequence

-403585738

-2092042741

-333693675

-331823022

1651689643

133526058

I ran the same code again at 10:30, and got this:

i = 0i = 1

i = 2

i = 3

i = 4i = 5

Page 34: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

What’s a Seed?What’s a Seed?

Random number sequence

-1517918040

1115789266

-208917030

1019800440

-6116528751

1362132786

I ran this code at 10:35Random randomGenerator = new Random(1234); for (int i = 0; i < 10; i++) System.out.println(randomGenerator.nextInt());

i = 0i = 1

i = 2

i = 3

i = 4i = 5

Page 35: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

What’s a Seed?What’s a Seed?

Random number sequence

-1517918040

1115789266

-208917030

1019800440

-6116528751

1362132786

I ran this code at 10:45 and got the same sequence.Random randomGenerator = new Random(1234); for (int i = 0; i < 10; i++) System.out.println(randomGenerator.nextInt());

i = 0i = 1

i = 2

i = 3

i = 4i = 5

Page 36: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Using Java’s RNGs (cont.)Using Java’s RNGs (cont.)

java.util.Randomjava.util.Random– Constructors:Constructors:

» Random()Random()» Random(long seed)Random(long seed)

– Methods:Methods:» nextInt()nextInt() random in (-2random in (-23131, 2, 23131-1)-1)» nextInt(int n)nextInt(int n) random in [0, n)random in [0, n)» nextFloat()nextFloat() random in [0, 1)random in [0, 1)» setSeed(long seed)setSeed(long seed)

java.lang.Mathjava.lang.Math– static double random()static double random() random in [0, 1.0)random in [0, 1.0)

Page 37: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Random Numbers In Action:Random Numbers In Action:The Monte Hall ParadoxThe Monte Hall Paradox

Monte Hall hosts a TV game Monte Hall hosts a TV game show, “Let’s Make a Deal”.show, “Let’s Make a Deal”.

One contestant is shown three One contestant is shown three doors.doors.

Behind one of the doors is a Behind one of the doors is a ““Fabulous Grand Prize”.Fabulous Grand Prize”.

Behind the other two doors are “worthless Behind the other two doors are “worthless prizes”. prizes”.

Page 38: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The Monte Hall ParadoxThe Monte Hall Paradox

The contestant selects a door.The contestant selects a door. Monte opens a door Monte opens a door notnot selected by the selected by the

contestant, and this always shows a contestant, and this always shows a worthless prize.worthless prize.

The contestant can choose to change her The contestant can choose to change her selection to the other door selection to the other door notnot opened by opened by Monte Hall.Monte Hall.

Should the contestant change doors?Should the contestant change doors?

Page 39: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The Monte Hall ParadoxThe Monte Hall Paradox

Very intelligent people are confused!Very intelligent people are confused!– Any initial door choice has a 1/3 chance of Any initial door choice has a 1/3 chance of

winning.winning.– Why would changing the door choice increase Why would changing the door choice increase

or decrease the odds of winning the “Fabulous or decrease the odds of winning the “Fabulous Grand Prize”?Grand Prize”?

– Can’t we settle this with a computer Can’t we settle this with a computer simulation?simulation?

Page 40: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The Door ClassThe Door Class

public class Door { boolean open; boolean hasGrandPrize; boolean chosenByContestant;}

Page 41: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The Game ClassThe Game Classimport java.util.*;public class Game { Door door1, door2, door3; void setUpGame() { door1 = new Door();door2 = new Door();door3 = new Door(); // initialize all the Door variables to false

Random r = new Random(); int grandPrizeDoor = r.nextInt(3); switch(grandPrizeDoor) { case 0: door1.hasGrandPrize = true; break; case 1: // etc. }}

Page 42: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Reality Check For Game ClassReality Check For Game Class void printStateOfDoors() { System.out.println("Door 1 is " + (door1.open ? " open, " : "not open, ") + (door1.hasGrandPrize ? "is the grand prize, and " : "is not the grand prize, and ") + (door1.chosenByContestant ? "is chosen." : "is not chosen.") ); System.out.println("Door 2 is " + (door2.open ? " open, " : "not open, ") + (door2.hasGrandPrize ? "is the grand prize, and " : "is not the grand prize, and ") + (door2.chosenByContestant ? "is chosen." : "is not chosen.") ); System.out.println("Door 3 is " + (door3.open ? " open, " : "not open, ") + (door3.hasGrandPrize ? "is the grand prize, and " : "is not the grand prize, and ") + (door3.chosenByContestant ? "is chosen." : "is not chosen.") ); }

Page 43: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The Game ClassThe Game Classpublic class Game { Door door1, door2, door3; void setUpGame() { // shown earlier} void contestantChooseDoor() { Random r = new Random(); int contestantDoor = r.nextInt(3); switch(contestantDoor) { case 0: door1.chosenByContestant = true; break; case 1: door2.chosenByContestant = true; break; case 2: door3.chosenByContestant = true; break; } }}

Page 44: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The PlayManyGames ClassThe PlayManyGames Classpublic class PlayManyGames { public static void main(String[] args) { Game theGame = new Game(); theGame.setUpGame(); theGame.printStateOfDoors(); theGame.contestantChooseDoor(); theGame.printStateOfDoors(); }}

Page 45: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

A Problem: First RunA Problem: First RunDoor 1 is not open, is not the grand prize, and is not chosen.Door 2 is not open, is not the grand prize, and is not chosen.Door 3 is not open, is the grand prize, and is not chosen.

Door 1 is not open, is not the grand prize, and is not chosen.Door 2 is not open, is not the grand prize, and is not chosen.Door 3 is not open, is the grand prize, and is chosen.

Page 46: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

A Problem: Second RunA Problem: Second RunDoor 1 is not open, is not the grand prize, and is not chosen.Door 2 is not open, is the grand prize, and is not chosen.Door 3 is not open, is not the grand prize, and is not chosen.

Door 1 is not open, is not the grand prize, and is not chosen.Door 2 is not open, is the grand prize, and is chosen.Door 3 is not open, is not the grand prize, and is not chosen.

Page 47: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

A Problem: Third RunA Problem: Third RunDoor 1 is not open, is the grand prize, and is not chosen.Door 2 is not open, is not the grand prize, and is not chosen.Door 3 is not open, is not the grand prize, and is not chosen.

Door 1 is not open, is the grand prize, and is chosen.Door 2 is not open, is not the grand prize, and is not chosen.Door 3 is not open, is not the grand prize, and is not chosen.

Page 48: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The SolutionThe Solution

The RNGs in both methods of the Game The RNGs in both methods of the Game class are starting from the same seed.class are starting from the same seed.

Solution: Take the RNG out of the methods, Solution: Take the RNG out of the methods, and into the Game class itself.and into the Game class itself.

But each But each instanceinstance of the Game class will of the Game class will stillstill start at the same place. start at the same place.

Solution: Make the RNG a Solution: Make the RNG a staticstatic variable. variable.

Page 49: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

The New Game ClassThe New Game Classpublic class Game { Door door1, door2, door3; static Random r = new Random(); void setUpGame() { int grandPrizeDoor = r.nextInt(3); switch(grandPrizeDoor) { // etc. } void contestantChooseDoor() { int contestantDoor = r.nextInt(3); switch(contestantDoor) { // etc. }}

Page 50: Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 2: Program Control

Completing the SimulationCompleting the Simulation

Add Add GameGame methods for methods for– Monte choosing a door to openMonte choosing a door to open– The player switching or notThe player switching or not– Deciding if the player has wonDeciding if the player has won

Add Add PlayManyGamesPlayManyGames code to code to– Call the new Game methodsCall the new Game methods– Put everything in a loopPut everything in a loop– Prompt the user for # of trials, switching policyPrompt the user for # of trials, switching policy– Display the resultsDisplay the results