Presentation is loading. Please wait.

Presentation is loading. Please wait.

Five-Minute Review What are expression statements? Compound statements? What is a scope? What are conditional statements in Java? How about iterative statements?

Similar presentations


Presentation on theme: "Five-Minute Review What are expression statements? Compound statements? What is a scope? What are conditional statements in Java? How about iterative statements?"— Presentation transcript:

1 Five-Minute Review What are expression statements? Compound statements? What is a scope? What are conditional statements in Java? How about iterative statements? In conditionals, why should we use compound statements instead of simple statements? What is the repeat-until-sentinel pattern? Expression statements: expressions can be made into a statement by terminating the expression with a semicolon (;), they encompass assignment expressions, ++/--, method invocations, object creation expressions. Compound statements: also called blocks, a sequence of statements in curly braces The scope of a variable is where it is visible. Local variables are visible from declaration until the end of the enclosing block/method; variables declared in loop header are visible in loop body. Conditional: if, if-else, switch-case. Iterative: for, while, do-while To avoid dangling else problem If the input contains a specific sentinel, use the if and break statements to exit the loop

2 Guide to Success I Throughout the semester:
Attend class, ask questions Work through corresponding book chapter, either before or after material is covered in class Solve programming tasks and align with concepts in class/book; ask for help whenever needed, but write your own code At the end of each lecture/chapter, first answer Review Questions in book yourself, then compare with solutions Participate in Practice Exam (last Globalübung in December)

3 Guide to Success II Ask each other if anything is unclear
Get connected, join social media Form study groups (ideal size: 2 – 3) Ask each other if anything is unclear Ask each other 5-Minute Review questions from slides, in random order Ask each other Review Questions from book, in random order; compare with solutions Ask each other questions on program assignments, as in mini exams

4 Guide to Success III When studying for practice/final exam:
Start on time Re-read chapter summaries Go through lecture slides Write notes, condense them to one page

5 Programming – Lecture 5 Methods (Chapter 5) Message paradigm
Functions, Math class Writing methods Mechanics of method calls Decomposition, train example

6 Recall (Chapter 2): Sending Messages to Objects
receiver.name(arguments); public class HelloProgram extends GraphicsProgram { public void run() { GLabel label = new GLabel("hello, world", 100, 75); label.setFont("SansSerif-36"); label.setColor(Color.RED); add(label); } label hello, world public class HelloProgram extends GraphicsProgram { public void run() { GLabel label = new GLabel("hello, world", 100, 75); label.setFont("SansSerif-36"); label.setColor(Color.RED); add(label); } The following program illustrates sending a message to an object. Note that the label doesn’t appear until it is added to the canvas. label hello, world hello, world hello, world HelloProgram hello, world skip simulation

7 Methods receiver.name(arguments); calling, returning, result
information hiding methods vs. programs role in expressions static methods

8 Math Class Math.abs(x) Returns the absolute value of x Math.min(x, y)
Returns the smaller of x and y Math.max(x, y) Returns the larger of x and y Math.sqrt(x) Returns the square root of x Math.log(x) Returns the natural logarithm of x (loge x ) Math.exp(x) Returns the inverse logarithm of x (e x ) Math class is included in standard package java.lang Math.pow(x, y) Returns the value of x raised to the y power (x y ) Math.sin(theta) Returns the sine of theta, measured in radians Math.cos(theta) Returns the cosine of theta Math.tan(theta) Returns the tangent of theta Math.asin(x) Returns the angle whose sine is x Math.acos(x) Returns the angle whose cosine is x Math.atan(x) Returns the angle whose tangent is x Math.toRadians(degrees) Converts an angle from degrees to radians Math.toDegrees(radians) Converts an angle from radians to degrees

9 Aside: Efficiency for (int i = 0; i <= Math.pow(2, n + 1) - 1;
Problems: Re-computes upper loop bound on every iteration Unneeded, costly method call to math library int i_cnt = (1 << (n + 1)); for (int i = 0; i < i_cnt; i++) ... Advice: Pre-compute upper loop bound Use shift operation for fast int. op. when possible

10 The Power of Shift For integers i and n: i << n
corresponds to i * 2n E.g. x << 3 corresponds to x * 8 i >> n corresponds to i / 2n 1 << n corresponds to 2n and is typically much faster than Math.pow(2, n)

11 Writing Methods scope type name(argument list) {
statements in the method body } private vs. public scope procedures: type void

12 return expression; private int max(int x, int y) { if (x > y) {
return x; } else { return y; }

13 private int factorial(int n) {
int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result;

14 Nonnumeric Methods private String weekdayName(int day) {
switch (day) { case 0: return "Sunday"; case 1: return "Monday"; case 2: return "Tuesday"; case 3: return "Wednesday"; case 4: return "Thursday"; case 5: return "Friday"; case 6: return "Saturday"; default: return "Illegal weekday"; }

15 Methods Returning Graphical Objects
private GOval createFilledCircle (int x, int y, int r, Color color) { GOval circle = new GOval(x - r, y - r, 2 * r, 2 * r); circle.setFilled(true); circle.setColor(color); return circle; }

16 Predicate Methods private boolean isDivisibleBy( int x, int y) {
return x % y == 0; } for (int i = 1; i <= 100; i++) { if (isDivisibleBy(i, 7)) { println(i); }

17 for (int i = 1; i <= 100; i++) { if (isDivisibleBy(i, 7) == true) {
println(i); } Write instead: if (isDivisibleBy(i, 7)) { Using Predicate Methods Effectively New programmers often seem uncomfortable with Boolean values and end up writing ungainly code. For example, a beginner might write isDivisibleBy like this: While this code is not technically incorrect, it is inelegant enough to deserve the bug symbol. A similar problem occurs when novices explicitly check to see if a predicate method returns true. You should be careful to avoid such redundant tests in your own programs.

18 private boolean isDivisibleBy( int x, int y) {
if (x % y == 0) { return true; } else { return false; } Write instead: return x % y == 0;

19 Testing Powers of Two private boolean isPowerOfTwo(int n) {
if (n < 1) return false; while (n > 1) { if (n % 2 == 1) return false; n /= 2; } return true; Write a predicate method called isPowerOfTwo that takes an integer n and returns true if n is a power of two, and false otherwise. The powers of 2 are 1, 2, 4, 8, 16, 32, and so forth; numbers that are less than or equal to zero cannot be powers of two.

20 Mechanics of Method Calling
Evaluate arguments Copy arg values to parameters, in stack frame Evaluate statements in method body return substitutes value in place of call Discard stack frame, return to caller When you invoke a method, the following actions occur: Java evaluates the argument expressions in the context of the calling method. Java then copies each argument value into the corresponding parameter variable, which is allocated in a newly assigned region of memory called a stack frame. This assignment follows the order in which the arguments appear: the first argument is copied into the first parameter variable, and so on. Java then evaluates the statements in the method body, using the new stack frame to look up the values of local variables. When Java encounters a return statement, it computes the return value and substitutes that value in place of the call. Java then discards the stack frame for the called method and returns to the caller, continuing from where it left off.

21 How many ways are there to select two coins?
To illustrate method calls, the text uses a function C(n, k) that computes the combinations function, which is the number of ways one can select k elements from a set of n objects. Suppose, for example, that you have a set of five coins: a penny, a nickel, a dime, a quarter, and a dollar: penny + nickel nickel + dime dime + quarter quarter + dollar penny + dime nickel + quarter dime + dollar penny + quarter nickel + dollar penny + dollar

22 n ! C(n, k) = k ! x (n – k) ! private int combinations( int n, int k) { return factorial(n) / (factorial(k) * factorial(n - k)); } Fortunately, mathematics provides an easier way to compute the combinations function than by counting all the ways. The value of the combinations function is given by the formula Given that you already have a factorial method, is easy to turn this formula directly into a Java method, as follows: The next slide simulates the operation of combinations and factorial in the context of a simple run method.

23 At this point, the program calls the combinations method, as follows:
public void run() { int n = readInt("Enter number of objects in the set (n): "); int k = readInt("Enter number to be chosen (k): "); println("C(" + n + ", " + k + ") = " + combinations(n, k) ); } n k 2 5 public void run() { int n = readInt("Enter number of objects in the set (n): "); int k = readInt("Enter number to be chosen (k): "); println("C(" + n + ", " + k + ") = " + combinations(n, k) ); } private int combinations(int n, int k) { return factorial(n) / ( factorial(k) * factorial(n - k) ); } n k private int factorial(int n) { int result = 1; for ( int i = 1 ; i <= n ; i++ ) { result *= i; } return result; n result 2 i private int factorial(int n) { int result = 1; for ( int i = 1 ; i <= n ; i++ ) { result *= i; } return result; n result 3 i private int factorial(int n) { int result = 1; for ( int i = 1 ; i <= n ; i++ ) { result *= i; } return result; n result 5 i 120 2 6 10 n k 5 2 2 5 120 24 2 2 1 6 1 1 2 6 5 4 1 2 3 1 3 1 2 2 3 6 4 At this point, the program calls the combinations method, as follows: The program makes another call to factorial, with k as its argument. The program now calls the factorial method, applying the same process. The program calls factorial yet again with n - k as its argument. 1. Evaluate the arguments n and k to get the integers 5 and 2. The factorial method returns the value 120 to its caller. This call to factorial returns the value 2. The final call to factorial returns the value 6. 2. Create a new frame for the combinations method. 3. Initialize the parameter variables n and k to the argument values. Combinations Enter number of objects in the set (n): 5 Enter number to be chosen (k): 2 C(5, 2) = 10 skip simulation

24 Decomposition Complete Task Subtask 1 Subtask 2 Subtask 3 Subtask 2a
One of the most important advantages of methods is that they make it possible to break a large task down into successively simpler pieces. This process is called decomposition. Before you start writing any code, you should think about the problem with an eye toward breaking the complete task into simpler subtasks. Suppose, for example, that you have been given a large task that seems too large to code as a single run method. Once you have completed the decomposition, you can then write a method to implement each subtask. Subtask 2a Subtask 2b

25 public void run() { Draw the engine. Draw the boxcar.
DrawTrain Drawing a Train As its primary illustration of decomposition, the text uses the problem of writing a GraphicsProgram to draw a train: Although it would be possible to write a single run method to draw the necessary graphical objects, such a program would be very difficult to read. Fortunately, the problem has a natural decomposition, at least at the first level: public void run() { Draw the engine. Draw the boxcar. Draw the caboose. }

26 Parameters Assumptions Caller supplies location of each car
DrawTrain Assumptions Caller supplies location of each car Train cars are same size, have same structure Engines are black Boxcars come in many colors Cabooses are red These assumptions imply that the headers for drawEngine, drawBoxcar, and drawCaboose will look like this: private void drawEngine( double x, double y) private void drawBoxcar( double x, double y, Color color) private void drawCaboose(

27 Frame, wheels, connector Drawn by drawCarFrame Differences
DrawTrain Commonalities Frame, wheels, connector Drawn by drawCarFrame Differences Engine: black, adds smokestack, cab, cowcatcher Boxcar: colored as specified by caller, adds doors Caboose: red, adds cupola. Looking for Common Features Another useful strategy in choosing a decomposition is to look for features that are shared among several different parts of a program. Such common features can be implemented by a single method. You can use a single drawCarFrame method to draw the common parts of each car, as described in the text.

28 Summary Motivation for methods: Mental models of method call:
Code re-use Decomposition Information hiding Mental models of method call: Message exchange Functional evaluation Distinguish public and private methods Local variables: variables declared in a method Different methods may have local variables with same name Method calls usually involve a receiving object; static methods are associated only with class


Download ppt "Five-Minute Review What are expression statements? Compound statements? What is a scope? What are conditional statements in Java? How about iterative statements?"

Similar presentations


Ads by Google