iteration. adding cds to vic stack in many of the programs you write, you would like to have a cd on...

18
Iteration

Upload: carol-lamb

Post on 29-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Iteration

Page 2: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Adding CDs to Vic Stack• In many of the programs you write, you would like to have a CD on the stack before the

program runs. To do this, you could edit the Vic class: • This section of code is a little more than half way down the file (Vic.java)

// start with up to 2 CDs on the stackif (random.nextInt (3) > 0) // 2 times out of 3{ theStack.push ("GarthB");

if (random.nextInt (2) == 0) // 1 time out of 3theStack.push ("LyleL");

}

You could FIND it by searching for theStack.push

Notice that it is random whether a CD gets pushed onto the stack or not. This is why the stack is sometimes empty.

Either remove the if statements that make it random whether a CD shows up or just add a few extra theStack.push(“OkGo”); statements outside of the if statements. Either way, you can change the names of the CDs to something you like more.

By the way… Have you played with the graphics in this class yet? You should try!

Page 3: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

fillOneSlot – 2 ways 2 do it

• To fill one slot (and ONLY one slot) there are two main schools of thought

Page 4: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Short-circuitingMove until you are at the end (no slot)

or see an empty slot (no CD).

while(seesSlot() && seesCD())moveOn();

//Then choose whether to put a CD…

This only works if the compiler implements something known as ‘short-circuiting’. This means that if the first condition in the while statement seesSlot() is false, it won’t bother to check the second condition seesCD() since the overall result will be false either way. However, if the compiler does not ‘short-circuit’ both conditions are checked. When at the END space, you would get an error message since you are looking for a CD where there is no slot.

Page 5: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Using a boolean variableAnother approach is to remember when you put down a CD by using a Boolean instance variable.

boolean placedCD = false; //While I see a slot and have NOT placed a CD.while (seesSlot() && !placedCD) {

if(seesCD()){

//Write the code to react to a slot with a CD.}else{

//Write the code to react to a slot that is empty.}

}

Remember to change the variable placedCD to true when you actually place a CD!!

Page 6: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Notes on #9 – use fillOneSlot !!!• The book introduces a useful method to enable us to remember a location among

the slots.

String spot = getPosition();• Now that you have stored your position, you can do whatever and still find your

way back.

Don’t copy code here, just use a method you’ve already written!!!!!!

• To go back to the remembered position, we compare our current position, getPosition() to spot, and go back until they are equal.

We are comparing Strings, so we use the .equals() method instead of ==.

while ( ! spot.equals (getPosition()))backUp();

Page 7: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Spirals and CONSTANTS

• CONSTANTSprivate final int MAX = 100; We introduce a new keyword, final, which makes a

variable a CONSTANT, meaning it has its final value and cannot be changed. Using constants often makes code more readable.

• On the next slide are two ways to make a spiral. With that head start, how about accepting the challenge to make a ‘Hexagon spiral’ or even an almost ‘Circular spiral’ !!! BONUS POINTS!

Page 8: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

These do the same thing!int size = 1;while(size < MAX){

paint(90,size);paint(90,size);size++;

}

for(int size = 1; size<MAX; size++){

paint(90,size);paint(90,size);

}

These are set up to start drawing from the middle of the spiral. The length of the pieces increases every two legs. All turns for a square spiral are 90 degrees.

Page 9: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Getting input from user

• Scanner versionScanner keyboard = new Scanner(System.in);System.out.println("Enter an integer.");int input = keyboard.nextInt();

• JOptionPane versionString textInput = JOptionPane.showInputDialog

(“Enter an integer"); int input = Integer.parseInt(textInput);

• Don’t forget to add an import statement!!

Page 10: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Factor tree150

752

253

55

15

We’d normally stop here

But since the computer doesn’t know what numbers are prime, it’s easier to go one more step and stop when our num becomes 1.

We find a factor of two…So we divide 150 by 2 and get 75, we now look for factors of 75

We find a factor of three…So we divide 75 by 3 and get 25, we now look for factors of 25

We find a factor of five…

Page 11: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Start your code with commentingpublic class FactorGenerator{

/* * This method should return the LOWEST prime * factor of num. */

public int nextFactor(int num){

//Loop over possible factors to test. Start at 2 up to num-1

//Use % to check if num is divisible by the possible factor. //return it if it is a factor!

//If the loop ends without finding a factor, then the number //must be prime, so return itself.

}

Page 12: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Start your code with commenting/* * This method should display all of the * factors of the parameter num */public void displayAllFactors(int num){

//Loop as long as there is another factor.

//get the next factor and print it //divide num by the factor.

}}

Page 13: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Primes

The goal of this program is to print out all of the prime numbers up to and including a number entered by the user.

A number is prime if it is ONLY divisible by 1 and itself.

So to check if a number is prime, see if it is divisible by anything (other than 1 and itself)

Page 14: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Pseudo-code for primesHere’s how it could be done in one method...

//Get maximum number from user.

//Loop through numbers to test (from 2 to the maximum)

//assume this number is prime…//Loop through all possible divisors

//if the number is divisible (%) then it isn’t prime

//print it out if it is prime

Page 15: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Better pseudo-code for Primes public class PrimeGenerator{

public int getIntegerFromUser(String text){

//Code (see slide #9)}public boolean isPrime(int number){

//Code (the inner loop from previous slide)}public void displayPrimes(int maximum){

//Code (the outer loop from previous slide)}

}

Page 16: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Runner for the ‘better’ codepublic class PrimeRunner{

PrimeGenerator bob = new PrimeGenerator();int max = bob.getIntegerFromUser(“Enter max value”);bob.displayPrimes(max);

}

Page 17: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Making a simple gameimport javax.swing.JOptionPane;

public class BasicGame{ private String itsSecretWord = "duck"; private String itsUsersWord = "none";

public void playManyGames() { do { playOneGame(); }while (JOptionPane.showConfirmDialog

(null, "again?“) == JOptionPane.YES_OPTION); } //======================

public void playOneGame() { askUsersFirstChoice(); while (shouldContinue()) { showUpdatedStatus(); askUsersNextChoice(); } showFinalStatus(); } //======================

public void askUsersFirstChoice() { itsUsersWord = JOptionPane.showInputDialog ("Guess the secret word:"); } //======================

public void askUsersNextChoice() { askUsersFirstChoice();

// no need to write the coding again } //======================

public boolean shouldContinue() { return ! itsSecretWord.equals (itsUsersWord); } //======================

public void showUpdatedStatus() { JOptionPane.showMessageDialog (null, "That was wrong. Hint: It quacks."); } //======================

public void showFinalStatus() { JOptionPane.showMessageDialog (null, "That was right. \nCongratulations."); } //======================}

Code from JavaAuNaturel textbook

Page 18: Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you

Fun game projects (over break?)

• Guess number game• Give the user a limited

number of guesses to find a number between 1 and 100 (or any max you choose!)

• Reply with higher or lower after each guess.

• Mastermind • Give the user a limited

number of guesses to find a three digit number.

• Reply with #correct and #correct but wrong location after each guess.

Details and possible code for these appear in Chapter 4 of JavaAuNaturel