Iteration - bcsc.k12.in.us

Iteration - bcsc.k12.in.us

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 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 stack if (random.nextInt (3) > 0) // 2 times out of 3 { theStack.push ("GarthB"); if (random.nextInt (2) == 0) // 1 time out of 3 theStack.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! fillOneSlot 2 ways 2 do it To fill one slot (and ONLY one slot) there are two main schools of thought Short-circuiting Move 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 shortcircuiting. This means that if the first condition in the while statement seesSlot() is false, it wont 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. Using a boolean variable Another 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!! 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. Dont copy code here, just use a method youve 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(); Spirals and CONSTANTS CONSTANTS private 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! These do the same thing! int size = 1; while(size < MAX)

{ paint(90,size); paint(90,size); size++; } for(int size = 1; size

Scanner version Scanner keyboard = new Scanner(System.in); System.out.println("Enter an integer."); int input = keyboard.nextInt(); JOptionPane version String textInput = JOptionPane.showInputDialog (Enter an integer"); int input = Integer.parseInt(textInput); Dont forget to add an import statement!! Factor tree 150 We find a factor of two 2

We find a factor of three 75 25 3 We find a factor of five So we divide 150 by 2 and get 75, we now look for factors of 75 5 But since the computer doesnt know what numbers are prime, its easier to go one more step and stop

when our num becomes 1. So we divide 75 by 3 and get 25, we now look for factors of 25 5 5 Wed normally stop here 1 Start your code with commenting public 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. } 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. } } 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) Pseudo-code for primes Heres 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 isnt prime //print it out if it is prime 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) } } Runner for the better code public class PrimeRunner { PrimeGenerator bob = new PrimeGenerator(); int max = bob.getIntegerFromUser(Enter max value); bob.displayPrimes(max);

} Making a simple game import javax.swing.JOptionPane; public void askUsersFirstChoice() { itsUsersWord = JOptionPane.showInputDialog ("Guess the secret word:"); } //====================== public class BasicGame { private String itsSecretWord = "duck"; private String itsUsersWord = "none"; public void askUsersNextChoice()

{ askUsersFirstChoice(); // no need to write the coding again } //====================== public void playManyGames() { do { playOneGame(); }while (JOptionPane.showConfirmDialog (null, "again?) == JOptionPane.YES_OPTION); } //====================== public boolean shouldContinue() { return ! itsSecretWord.equals (itsUsersWord);

} //====================== public void playOneGame() { askUsersFirstChoice(); while (shouldContinue()) { showUpdatedStatus(); askUsersNextChoice(); } showFinalStatus(); } //====================== 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 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

Recently Viewed Presentations

  • Warm-ups for English 11

    Warm-ups for English 11

    List one synonym & antonym for each term. ... the citizens agree to abide by government laws and rules. In return, the government promises to protect the citizens' rights and freedoms. Benjamin Franklin, Thomas Paine, and Thomas Jefferson.
  • Windows 8 &amp; Windows Phone 8Round Table29th November 2012 ...

    Windows 8 & Windows Phone 8Round Table29th November 2012 ...

    Microsoft Confidential. Windows 8 & Windows Phone 8Round Table29th November 2012 Microsoft Developer & Platform Evangelism (DPE)- Eric Nelson, Technical Evangelist- Mike Taulty, Technical Evangelist- Zoe Redmond, Business Development- Andrew Bennett , Business Development- Rachael Beeston , Business DevelopmentMetia: Lizzie...
  • Prehistory Jigsaw Piece together an object and use

    Prehistory Jigsaw Piece together an object and use

    One of the object photos from slide 5 or 6 per pupil or small group, cut into pieces like a jigsaw. Activity overview: Give each pupil cut up pieces of . one . object from slides 5 and 6 which...
  • INCENSE

    INCENSE

    (This is a prophecy about Heaven) How is it going to be like in Heaven? More great features in heaven No cursing but blessing from God No darkness because God is the God of light No ignorance, but rather full...
  • Big Opportunity. Small Unit. Essential Flake and Nugget.

    Big Opportunity. Small Unit. Essential Flake and Nugget.

    Flake ice is a smart choice for applications ranging from blended cocktails and salad bars to produce, seafood and meat displays. Flake ice is also popular for therapeutic use in healthcare facilities. ... Scotsman provides a 3-year parts and labor...
  • Course handouts Introduction to Multilevel Models: Getting started

    Course handouts Introduction to Multilevel Models: Getting started

    Introduction to Multilevel Models: Getting started with your own data University of Bristol Monday 31ST March- Friday 4th April 2008 Resources 1.0 Introductions 2.00 Multilevel Data Structures Multilevel modelling is designed to explore and analyse data that come from populations...
  • Introduction: Ice Breaker - Indiana University Bloomington

    Introduction: Ice Breaker - Indiana University Bloomington

    Cognitive: what the respondent knows about the attitude object. Action: what the respondent will do with regard to the object of the attitude. Different wording may produce different results. Components of attitudes. S519
  • Quarterly Performance Report - Earth Resources

    Quarterly Performance Report - Earth Resources

    Summary. This report provides a summary of the operating performance for financial year 2018-19 Quarter 3 (1st January 2019 to 31st March 2019). Actions to improve the operation of the regulatory system include: