Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.

Similar presentations


Presentation on theme: "CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann."— Presentation transcript:

1 CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann

2 Michael Eckmann - Skidmore College - CS 106 - Spring 2007 Today’s Topics questions, comments? DecimalFormat class ternary conditional operator overloading methods recursion

3 this –is a way to explicitly say you are referring to an instance variable inside the same class –it contains the value of the “current object” –I'll show an example of this in the Movie class. if you name a parameter of a method the same name as an instance variable, you can –refer to the instance variable inside the method by using this. in front of it –refer to the parameter by it's name alone

4 ways to call methods a method that is defined in the same class as another method can call it by just using the method name and arguments in parentheses. we saw many examples of this: one was in the sorting program we wrote --- the swap method was defined in our class and was called like so swap(arr, i, i+1);

5 ways to call methods a static method that is defined in some class can be called by using the class name followed by the dot operator and then the method name and arguments in parentheses. Note: we don’t have to first define a reference to an object of that class. we’ve seen examples of this with the Integer.parseInt and JOptionPane.showMessageDialog methods (among many others) We do NOT need to declare a variable to hold a reference to an object of these classes, if all we want to do is call a static method in it. We call one of these like so: some_int = Integer.parseInt(some_str);

6 ways to call methods A public non-static method that is defined in some other class must be called by using a reference to the object of the class followed by the dot operator and then the method name and arguments in parentheses. we’ve seen examples of this with the Time1 class First we declare a variable to hold a reference to a Time1 object, then we can call one of Time1’s methods. E.g. Time1 starttime = new Time1(); System.out.println(" start time = " + starttime.getTime());

7 Recap - ways to call methods a method that is defined in the same class as another method can call it by just using the method name and arguments in parentheses. swap(arr, i, i+1); a method that is defined in some other class (from where it is being called) must be called by using a reference to the object of the class followed by the dot operator and then the method name and arguments in parentheses. Time1 starttime = new Time1(); System.out.println(" start time = " + starttime.getTime()); a static method that is defined in some class can be called by using the class name followed by the dot operator and then the method name and arguments in parentheses. some_int = Integer.parseInt(some_str);

8 DecimalFormat class Let's look online at the Java API for this class (and others) Allows us to make output nicer by rounding floats and doubles etc. for output Specify a pattern when creating an object of DecimalFormat class 0 vs. # – 0 is a required digit position To the left of decimal --- means at least that many To the right of decimal --- means exactly that many places – # to the right of decimal means that a 0 will not display. % at end of pattern causes number to be displayed as a percent E-notation is also possible (scientific notation)

9 DecimalFormat class DecimalFormat df = new DecimalFormat(“00.00”); To use it : (assuming we have a double var temperature) – df.format(temperature) /* this will return a String based on the value of temperature and the pattern specified when the df object was constructed */ – Since it returns a String we can place it anywhere a String can be like: – System.out.println(df.format(temperature));

10 DecimalFormat class Let's try a few different formats and see what is produced. Note: no truncation of numbers to the LEFT of the decimal point will ever occur with this formatting even if we have: – the format is 00.0# – assume the value to format is 365.2512 – The number will be formatted as 365.25 because the amount of 0's to the LEFT of the decimal in the format means at least that many places.

11 Ternary operator (acts like if /else ) –Ternary operator contains three parts separated by a ? and a : Example: int hour = 14, non_mil_hr; non_mil_hr = (hour == 12 || hour == 0) ? 12 : hour % 12 )

12 Exercise Let's use the DecimalFormat class and the ternary conditional operator to make the Time1 class's toString and ampmString methods more concise.

13 overloading methods recall that we overloaded the constructor --- what did that mean? we can do the same with any method.

14 overloading methods recall that we overloaded the constructor --- what did that mean? we can do the same with any method. –we give a method the same name but different number of parameters and/or types of parameters. Order matters. names of parameters do not. A method's signature must be unique. Signature includes name of method, and types of parameters in order. –e.g. public void meth1(int i, int j) public void meth1(int j) public void meth1(String s, int i, int j) public void meth1(int i, String s, int j) public void meth1(int j, int k) –// this last one not allowed b/c signature is same as first one.

15 Factorial method using iteration // non-recursive solution to the factorial problem public int compute_factorial(int num) { int temp_factorial=1; while (num > 0) { temp_factorial = temp_factorial * num; num--; } return temp_factorial; }

16 Factorial method using iteration Let's put this in a program and call it.

17 Recursion A recursive method is a method that calls itself (directly or indirectly.) Recursion is often used when the problem to be solved can be easily implemented with recursion as opposed to an iterative technique. All problems that can be solved recursively can be solved iteratively. Sometimes though the iterative solution might be very long and require lots of code. In that case recursion might be preferred because it is more readable and easier to write.

18 Recursion Let’s say we know the solution to some case of a problem. If we want to find a solution to a slightly more complex case of the problem, we might be able to use the solution to the easier problem as part of our solution to the more complex problem. For example, if we know the factorial of the number 6, to find the factorial of 7, we can just multiply 7 * the factorial of 6, so 7! = 7 * 6!. Here, the solution we know (6! = 720) is used as part of the solution to 7!, which is 7*720 = 5040.

19 Recursion So, more generally, if we know the solution to (n-1)! We can easily find the solution to n! by just multiplying n*(n-1)!. In addition to knowing this though, we need to also know that 1! = 1. This is the simplest factorial. Now, powered with the knowledge that – 1! = 1 and – the fact that given (n-1)!, we can compute n! we have enough information to compute the factorial of any positive integer. Do we all agree?

20 Recursion This is a recursive solution to the factorial problem because we know how to solve the simplest case (1!) and we know how to solve a more complex case given a solution to a slightly less complex case (n! = n*(n- 1)! ).

21 Factorial method using recursion public int compute_factorial ( int num ) { if ( num <= 1 ) return 1; else return num * compute_factorial ( num - 1) ; } // this recursive method is based on figure 6.12 // in Deitel and Deitel.

22 Factorial method using recursion When the recursive method is called, if the number passed in as an argument is less than or equal to 1, then 1 is returned and the method ends. That is known as the base case. If the number passed in as an argument is greater than 1, then the else portion of the method is executed. This says to return that number times the result of another call to the method with the argument of one less than the original value. The else portion in this method is known as the recursion step.

23 Factorial method using recursion Let’s examine what happens when the number 2 is passed in as an argument to compute_factorial. int fact_value; fact_value = compute_factorial( 2 ); The method would check if 2 <= 1 and since that is false, the else portion would execute. The else portion calls compute_factorial(1). This second call to the method invokes another “copy” of the method. This second call checks if 1 <= 1 and this is true so it returns 1.

24 Factorial method using recursion This value of 1 gets returned to the most recent call (and hence the second call to the method ends its execution.) This value of 1 gets multiplied by 2. This happens in the else portion of the method. The result, 2, gets returned to the original call of the method (and hence the first call to the method ends its execution.) If compute_factorial was called with the number 3 as an argument, the method would end up being called three times.

25 Recursion When the method is recursively called in the else portion, the prior call to the method has not finished executing. It is waiting on the result of this new method call. There will be multiple active copies of the recursive method when the else portion executes. The recursion ends when the base case is finally met. The base case then returns a result to the previous call of the method and a sequence of returns occurs until the original method call gets its returned value.

26 Factorial method using recursion Let’s look at a program that will illustrate, through print statements, what happens in what order when a method is called recursively.

27 Recursion We may come back to recursion in other problems later in the semester. Understand that the Factorial example, was for instructional purposes only, since it is a very simple example of recursion. For the factorial method, in practice, we would always prefer the non-recursive (iterative) solution. It is more efficient in terms of both time and space. Recursive solutions often take more time to run, because making a method call is slower and requires more memory than doing the same statements without a method call.

28 Recursion Direct vs. indirect recursion – When a method calls itself, it is direct recursion – When method1 calls method2 and method2 calls method1, it is indirect. – There can be more than just two methods involved in the indirection.


Download ppt "CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann."

Similar presentations


Ads by Google