Shlomo Hershkop Basics overview
Shlomo Hershkop Basic Review - Overview Practice coding Practice coding finger guessing game finger guessing game Useful classes Useful classes Vector class Vector class Random Random Practice Practice Rolling dice game Rolling dice game Slot machine simulation Slot machine simulation Iterators Iterators
Shlomo Hershkop Reminder Lets just review some of the basics and get to some code Lets just review some of the basics and get to some code
Shlomo Hershkop control You can control a code block (commands between braces) You can control a code block (commands between braces) if condition statement if condition statement while loop statement while loop statement
Shlomo Hershkop Exceptions Can look for problems by surrounding your code with try and catch blocks Can look for problems by surrounding your code with try and catch blocks The Exception class, is the most general exception, will always catch everything The Exception class, is the most general exception, will always catch everything
Shlomo Hershkop random Many times in programming would like to get a random number Many times in programming would like to get a random number Can ask the user for it Can ask the user for it Use a built in library which produces pseudo random numbers Use a built in library which produces pseudo random numbers
Shlomo Hershkop Math.random() Math.random() So what is this ? So what is this ?
Shlomo Hershkop Math.random() Math.random() Math class Math class It’s a static method since we don’t create an instance of the math class to get to it It’s a static method since we don’t create an instance of the math class to get to it
Shlomo Hershkop Next Lets write a small program Lets write a small program Will want to simulate a game, say tossing a few dice Will want to simulate a game, say tossing a few dice Say you have 2 users, who ever has more points wins! Say you have 2 users, who ever has more points wins!
Shlomo Hershkop Eclipse 1. Start Eclipse 2. Start a new project (right click in project explorer) 3. Double click, right click on default package and start a new class 4. Call it DiceTest 1. Check off that you want comments 2. Check off you want a main
Shlomo Hershkop Next Create a class called Dice Create a class called Dice Check off you want comments Check off you want comments Should have two members: Should have two members: private final int MAX = 8;//8 sided dice private final int MAX = 8;//8 sided dice private int faceValue;//the face of the die private int faceValue;//the face of the die Create empty constructor Create empty constructor Will be initializing the die, choose any number less than the MAX Will be initializing the die, choose any number less than the MAX
Shlomo Hershkop More stuff Need to add a method Need to add a method roll() roll() This will simulate a dice roll This will simulate a dice roll How to write this ? Any ideas ? How to write this ? Any ideas ?
Shlomo Hershkop public void roll () { public void roll () { faceValue = (int)(Math.random() * MAX +1) faceValue = (int)(Math.random() * MAX +1) notice the cast …. ?? notice the cast …. ?? Why the +1 Why the +1
Shlomo Hershkop next Need to add accessor methods to get the face value Need to add accessor methods to get the face value Also lets define a toString method to allow us to print it out Also lets define a toString method to allow us to print it out
Shlomo Hershkop public int getFace(){ public int getFace(){ return faceValue; } public String toString(){ public String toString(){ return “face: “ + faceValue; }
Shlomo Hershkop One more Lets add a way to set the dice face Lets add a way to set the dice face Important to make sure that it isn’t more than max!! Important to make sure that it isn’t more than max!!
Shlomo Hershkop code public void setFace(int val) throws Exception { public void setFace(int val) throws Exception { if(val > MAX){ if(val > MAX){ throw new Exception(“too high value”); throw new Exception(“too high value”);} faceValue = val; }
Shlomo Hershkop Back to main Ok how would main look like ? Ok how would main look like ? We want to toss the dice twice for each user and add up their results to see who is the winner We want to toss the dice twice for each user and add up their results to see who is the winner Start coding… Start coding…
Shlomo Hershkop Dice d1,d2; int user1,user2; d1 = new Dice(), d2 = new Dice(); d1.roll(); d2.roll(); user1 = d1.getFace() + d2.getFace(); //roll again for user 2 d1.roll(); d2.roll(); user2 = d1.getFace() + d2.getFace(); //now compare if( user1 > user2) { System.out.println(“User 1 has won with “ + user1); System.out.println(“User 1 has won with “ + user1); } else if (user2 > user1) { System.out.println(“User 2 has won with “ + user2); } else { System.out.println(“It was tied at “ + user1); }
Shlomo Hershkop Make sure it compiles correctly Make sure it compiles correctly Now run it correctly Now run it correctly Now print out both dice at users to see how each user received the points they did Now print out both dice at users to see how each user received the points they did
Shlomo Hershkop Next In your main, call the setFace method and get it to compile In your main, call the setFace method and get it to compile
Shlomo Hershkop Moving on How would you adopt the code to run over say 5 dice without having to create 5 variables ?? How would you adopt the code to run over say 5 dice without having to create 5 variables ?? Please discuss it with who ever is sitting next to you Please discuss it with who ever is sitting next to you
Shlomo Hershkop solution Work with dice arrays Work with dice arrays Dice []game = new Dice[5]; Dice []game = new Dice[5]; for( int i=0; i < 5; i++){ for( int i=0; i < 5; i++){ game[i] = new Dice(); } Same for rolling and adding results Same for rolling and adding results
Shlomo Hershkop Back to theory Vector class Vector class Iterators Iterators
Shlomo Hershkop Vector Class Arrays allow you to hold a specific amount of things Arrays allow you to hold a specific amount of things But need to know ahead of time how many But need to know ahead of time how many Would like to have an array which don’t need to know how many items will hold Would like to have an array which don’t need to know how many items will hold
Shlomo Hershkop Vector Vector vec = new Vector(); Vector vec = new Vector(); vec.add(10); vec.add(10); vec.add(23); vec.add(23); etc etc Then can say something like Then can say something like vec.size(); vec.size(); vec.elementAt(0); vec.elementAt(0); vec.remove(2); vec.remove(2);
Shlomo Hershkop Iterator Iterator is an object which allows you to step through (and maybe modify) a collection of objects in some order without knowing the underlying representation. Iterator is an object which allows you to step through (and maybe modify) a collection of objects in some order without knowing the underlying representation. Allows loose coupling between collections and users. Allows loose coupling between collections and users. Simplest example: Simplest example: We want to walk through the vector, but don’t want to depend on the size when we start We want to walk through the vector, but don’t want to depend on the size when we start Imagine someone might be adding things into the vector as we are looking at it Imagine someone might be adding things into the vector as we are looking at it
Shlomo Hershkop Iterator Simple Simple Can call a method called Can call a method called hasNext() hasNext() Tell us if there is something else Tell us if there is something else next() next() Get the next item Get the next item
Shlomo Hershkop Vector Iterator Iterator ourIter = somevec.iterator(); Iterator ourIter = somevec.iterator(); while( ourIter.hasNext() ){ while( ourIter.hasNext() ){ Object obj = ourIter.next(); Object obj = ourIter.next(); So something with obj So something with obj }
Shlomo Hershkop More code Lets have some fun Lets have some fun Imagine you have a slot machine Imagine you have a slot machine Say you get a random number when you play the machine Say you get a random number when you play the machine Only get payoff if you hit a prime number Only get payoff if you hit a prime number Say 0 – 100 Say 0 – 100 What do we need to do to get this working ? What do we need to do to get this working ?
Shlomo Hershkop Useful method private boolean isPrime(int p) { private boolean isPrime(int p) { int i; int i; for(i=2; i<(p/2); i++) { for(i=2; i<(p/2); i++) { if ( i*(p/i) == p ) if ( i*(p/i) == p )return(false); } return(true); return(true); }
Shlomo Hershkop next Code the main class Code the main class SlotMachineGame SlotMachineGame Include main Include main Should define a max number Should define a max number Should have a way to roll the slot machine Should have a way to roll the slot machine Check if prime, if yes return payment (say 5) Check if prime, if yes return payment (say 5) Else return 0 (nothing) Else return 0 (nothing)
Shlomo Hershkop Question Can you write the program so that if you play the game 50 times in a row (say it costs you a dollar to play) Can you write the program so that if you play the game 50 times in a row (say it costs you a dollar to play) Will I come out ahead at the end ?? Will I come out ahead at the end ?? What about playing 40 times in a row ? What about playing 40 times in a row ?
Shlomo Hershkop Thanks and hoped you had fun Thanks and hoped you had fun