1 / 103

Sound Check

Sound Check. Some Final Words on Methods. RECALL: Three major paradigms for programming. Java Methods. There exists in Java a single construct, the method , for both procedures and functions: when a procedure is called for, specify the return type “void” before method name

brasen
Télécharger la présentation

Sound Check

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. Sound Check

  2. Some Final Words on Methods

  3. RECALL: Three major paradigms for programming

  4. Java Methods • There exists in Java a single construct, the method, for both procedures and functions: • when a procedure is called for, specify the return type “void” before method name • public void printHelloWorld( ) • { • System.out.println(“Hello World!”); • } // of printHelloWorld • Note: All methods must have parentheses for parameters . . . even if no parameters! Quick Review

  5. Java Methods • Single construct for both procedures and functions: • when a function is called for, specify the • appropriate return type before method name • public float average (float fNum1, float fNum2, float fNum3) • { • float fReturnVal; • fReturnVal = • (fNum1 + fNum2 + fNum3)/ 3; • return (fReturnVal); • } // of average Quick Review

  6. Method Signatures • “The signature of a method consists of the name of the method and the number and types of formal parameters to the method. A class may not declare two methods with the same signature, or a compile time error occurs.” • --Java Language Specification s.8.4.2 • Method overloading occurs when identically named methods have different signatures. • public int getCube(int iNum){ • return iNum*iNum*iNum; • } • public int getCube(float fNum){ • return (int)(fNum*fNum*fNum); • } • public int getCube(double dNum){ • return (int) (dNum*dNum*dNum); • } Quick Review

  7. Parameters • Unlike Pseudocode, Java only has “in” parameters. • Thus no need to declare in, in/out or out ‘cause they’re all IN • Parameters do need to be declared just like variables: public void demo(int i, float x) • More about parameters when we discuss objects

  8. Where do Methods Go? Methods (and variables) are contained in Classes, as either class or instance members. More on creating classes and objects shortly . . . Quick Review class zippy { int pin; public String yow() { // some code } }

  9. Questions?

  10. Iteration

  11. Java Basics: Iteration Constructs • In Pseudocode, we had a single iteration construct, flexible enough to be used in all iteration contexts. Actually (if you were paying attention last semester) we talked about three kinds of loops: Sentinal Loops Test-Last Loop N-and-a-half Loops

  12. Java Basics: Iteration Constructs • In Pseudocode, we had a single iteration construct, flexible enough to be used in all iteration contexts. • Java, like most programming languages, does not provide a single flexible construct. • Instead, Java offers three special case loop constructs, each good for a particular context. • Do not get accustomed to only one of them and try to use it for all situations. • To use them wisely, you should consider not only how they work, but also when each is best used…

  13. Java Iteration Constructs: “While Loops” • When repeating steps, people naturally want to follow the pattern: • get a value, then process that value • The while loop construct calls for the unnatural pattern: • obtain the first loop control value before entering the loop itself; • then, within the loop body, • first do the process steps, • then do the get next steps

  14. Unnatural? while(You haven’t gotten to my street) { Keep going straight } turn right

  15. Java Iteration Constructs: “While Loops” Pseudocode: <get first value> loop exitif NOT(condition) <process value> <get next value> endloop Java example: <get first value> while (condition) { <process value> <get next value> } Pseudocode flavor: Sentinal

  16. Java Iteration Constructs: “Do While Loops” Java example: do { statement 1; ... statement N; } while (condition); Pseudocode: loop statement 1 ... statement N exitif (NOT(condition)) endloop Pseudocode flavor: Test Last

  17. Java Iteration Constructs: “For Loops” Java syntax: for (<initialization>; <continue if>;<increment>) Java example: int i; for (i=0; i<10; i++) { <some statements> } Pseudocode: i isoftype Num i <- 0 loop exitif (i =>10) <some statements> i <- i + 1 endloop

  18. i = 0; while (i < 10) { System.out.println(i); i++; } for(i = 0; i < 10; i++) { System.out.println(i); } Secret! A for Loop can be exactly written as a while loop This will help you understand the sequence of operations of a for loop

  19. Java Iteration Constructs: “For Loops” --Spins on ending semicolon; code in braces executed once! --variable declared inside for loop signature; caution: --the variable may be needed outside the for loop structure Common Problems with For Loops include: for (i=0; i<N; i++); { … } for (int i=0; i<N; i++){…}

  20. Potential Confusion public class Forex { static int i = 42; public static void main(String args[]) { for(int i=0; i < 5; i++) { System.out.println(i); } System.out.println(i); } }

  21. Output 0 1 2 3 4 42

  22. ASK: Is it simply a count of the number of iterations? Is it a value that the loop itself must compute? Is it a value that already exists somewhere, and the loop only obtains it from elsewhere? Java Iteration Constructs: When to Use --The term “control variable” refers to the variable whose value is tested to determine if the loop should continue for another iteration or halt. --For example, variable thisVar, below: while (thisVar < = SOME_CONSTANT) --To determine which loop construct is appropriate for a given situation, ask yourself “where does the control variable’s value come from?”

  23. Java Iteration Constructs: When to Use The for loop: used when the control variable is a simple count of the number of iterations, e.g.: “create a loop that reads and processes the next 100 numbers.” The while loop: used when the control variable has a value that already exists and is simply obtained by the loop. e.g.: “create a loop that reads in numbers and processes them until it reads in a 100.” The do-while loop: used when the control variable’s value must be calculated by the loop itself. e.g.: “create a loop that reads in numbers until their sum is greater than 100.”

  24. Java Iteration Constructs: Review Which loop construct would you use if... You need to perform a series of steps exactly N times? You need to traverse a linked list of unknown size, and stop when you find a certain value? You need to perform a series of steps at least once, and continue performing these steps for an an unknown number of times

  25. Iteration Reiteration • Three kinds of iteration • for (...;...;...) {...} loops • Fixed number of iterations • while (...) {...} loops • Iteration condition evaluated in advance • do {...} while (...) loops • Iteration condition evaluated in the loop

  26. Questions?

  27. Arrays of Primitives • The Idea: Same concepts you know from Pseudocode A few differences in implementation • Java array declaration: <elemType>[ ] <arrID> = new <elemType>[<size>]; e.g.: to declare an array of ten ints for storing numerical grades... int[ ] iGradeArray = new int[10]; • Array declaration error: using parentheses, not brackets, e.g., int[ ] iGradeArray = new int(10);

  28. Details • The odd looking syntax is because arrays (even arrays of primitives) are objects. • We'll explain in detail once we get to objects... int[ ] iGradeArray = new int[10]; int iGradeArray[ ] = new int[10];

  29. int[ ] iGradeArray = new int[10]; int i; // when declaring and manipulating arrays, // you may use the single-letter IDers // i, j, kfor indices due to convention // (everybody knows what it is) for (i=0; i < iGradeArray.length; i++) { iGradeArray[i] = 0; } // for loop Arrays • Example: • declare iGradeArray of 10 ints • initialize all 10 values to 0 Great idea! if you change the array size, you need only change the instantiation. • Notes: • Arrays know their own length • length is a field, not a method • Arrays are statically sized: you cannot change the length after declaration. • All arrays are objects, thus you must declare a reference, and instantiate it, and initializeit

  30. More Notes: • Array indices begin at 0, not at 1 • So, length is one greater than iMAX_INDEX • Thus, an error if you do: Arrays int[ ] iGradeArray = new int[10]; int i; for (i=1; i <= iGradeArray.length; i++) { iGradeArray[i] = 0; } // for loop • Code above attempts to access elements 1..10 • But... you have indices 0..9 • So: it misses the 1st element (which is at index 0) it tries to go past 10th element (which is at index 9)

  31. Questions?

  32. Sample Quiz Problem Given an array of ints, return the index of the largest element. Use the code below. public int getLargestIndex(int[ ] iArray){ /* YOUR CODE GOES HERE */ }

  33. Sample Quiz Problem Given an array of ints, return the index of the largest element. Use the code below. public int getLargestIndex(int[ ] iArray) { int iLargest = -9999; int iCounter; for (iCounter = 0; iCounter < iArray.length; iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest; }// getLargestIndex Does this work?

  34. Sample Quiz Problem Given an array of ints, return the index of the largest element. Use the code below. public int getLargestIndex(int[ ] iArray) { int iLargest = -9999; int iCounter; for (iCounter = 0; iCounter < iArray.length; iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest; }// getLargestIndex What if all the values are less than -9999

  35. Sample Quiz Problem Given an array of ints, return the index of the largest element. Use the code below. public int getLargestIndex(int[ ] iArray) { int iLargest = iArray[0]; int iCounter; for (iCounter = 0; iCounter < iArray.length; iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest; }// getLargestIndex How about this?

  36. Sample Quiz Problem Given an array of ints, return the index of the largest element. Use the code below. public int getLargestIndex(int[ ] iArray) { int iLargest = iArray[0]; int iCounter; for (iCounter = 1; iCounter < iArray.length; iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest; }// getLargestIndex Why not start out iCounter at 1, and not 0 like most for loops?

  37. Sample Quiz Problem Given an array of ints, return the index of the largest element. Use the code below. public int getLargestIndex(int[ ] iArray) { int iLargest = iArray[0]; int iCounter; for (iCounter = 1; iCounter < iArray.length; iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest; }// getLargestIndex Now it should be perfect!

  38. Sample Quiz Problem Given an array of ints, return the index of the largest element. Use the code below. NOTE THIS! public int getLargestIndex(int[ ] iArray) { int iLargest = iArray[0]; int iCounter; for (iCounter = 1; iCounter < iArray.length; iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest; }// getLargestIndex Test taking is about READING THE DIRECTIONS

  39. Sample Quiz Problem What’s the solution? This is a good problem to work out on your own. We don’t want the largest VALUE, we instead want the INDEX of the largest value.

  40. Lessons Learned Read the question carefully. Don’t fall into habits (e.g., all for loops must start with the counter at 0). Don’t make assumptions about input data (e.g., -99999 is NOT a good initial value). Trace your code; watch for simple >, < errors.

  41. Questions?

  42. The Road Ahead Today Recursion Classes and Objects Constructors Object References Parameters

  43. A Question How many people here don’t like recursion? Why not? A Promise: By the end of this lecture, you will say: “Recursion Rocks My World!”

  44. Recursion Let’s say you place two rabbits in a hutch. What’s going to happen?

  45. Two Months Later... original rabbits new rabbits If it takes two months for rabbits to reach maturity, in two months you’ll have one productive pair and one (brand new) non-productive pair. (This assumes all rabbits live up to their reputation.)

  46. The rabbits keep at it. 1 month old 0 months old The next month, you get another pair . . .

  47. Suppose What if: The rabbits always had two offspring, always male and female; Rabbits always reached maturity in two months; No rabbit dies. How many pairs of rabbits do you have in a year? 1 2 3

  48. Hare Raising Story KEY = one m/f pair End Month 1 End Month 2 End Month 3 End Month 4 End Month 5 Start

  49. Month Productive Non-Productive Total 1 0 1 1 2 1 0 1 3 1 1 2 4 2 1 3 5 3 2 5 6 5 3 8 7 8 5 13 8 13 8 21 9 21 13 34 10 34 21 55 11 55 34 89 12 89 55 144 Pairs of Rabbits See a pattern yet?

  50. Let’s Take Another Example • Instead of rabbits, let’s use geometry. • Draw a square of size 1. • Rotating 90 degrees, add to it a square of size 1. • Rotating 90 degrees again, add a square of size 2. • Again, rotate and add a square of size 3, and so on. • Keep this up for the sequence we noted in the table: • 1, 1, 2, 3, 5, 8, 13, 21, . . . , • What do you see?

More Related