1 / 18

Iteration

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)

simeon
Télécharger la présentation

Iteration

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Iteration

  2. 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!

  3. fillOneSlot – 2 ways 2 do it • To fill one slot (and ONLY one slot) there are two main schools of thought

  4. 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 ‘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.

  5. Using a boolean variable Another approach is to remember when you put down a CD by using a Boolean instance variable. booleanplacedCD = 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!!

  6. 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();

  7. Spirals and CONSTANTS • CONSTANTS private finalint 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!

  8. 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.

  9. Getting input from user • 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"); intinput = Integer.parseInt(textInput); • Don’t forget to add an import statement!!

  10. Factor tree 150 We find a factor of two… 2 75 So we divide 150 by 2 and get 75, we now look for factors of 75 We find a factor of three… 25 3 So we divide 75 by 3 and get 25, we now look for factors of 25 We find a factor of five… 5 5 We’d normally stop here 1 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. 5

  11. Start your code with commenting public class FactorGenerator { /* * This method should return the LOWEST prime * factor of num. */ public intnextFactor(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. }

  12. Start your code with commenting /* * This method should display all of the * factors of the parameter num */ public void displayAllFactors(intnum) { //Loop as long as there is another factor. //get the next factor and print it //divide num by the factor. } }

  13. 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)

  14. Pseudo-code for primes Here’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

  15. Better pseudo-code for Primes public class PrimeGenerator { public intgetIntegerFromUser(String text) { //Code (see slide #9) } public booleanisPrime(int number) { //Code (the inner loop from previous slide) } public void displayPrimes(int maximum) { //Code (the outer loop from previous slide) } }

  16. Runner for the ‘better’ code public class PrimeRunner { PrimeGenerator bob = new PrimeGenerator(); int max = bob.getIntegerFromUser(“Enter max value”); bob.displayPrimes(max); }

  17. Making a simple game import 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 booleanshouldContinue() { 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

  18. 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

More Related