1 / 83

Java Methods and Control Statements: Arrays and More

Learn about methods, control statements, arrays, and more in Java. Understand the benefits of methods, passing parameters, pass by value, method overloading, and more.

rcarlson
Download Presentation

Java Methods and Control Statements: Arrays and More

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. Syllabus (1) Methods, Control Statements, Arrays

  2. Syllabus (2)

  3. Chapter 4 Methods • Introducing Methods • Benefits of methods, Declaring Methods, and Calling Methods • Passing Parameters • Pass by Value • Overloading Methods • Ambiguous Invocation • Scope of Local Variables • Method Abstraction • The Math Class • Case Studies • Recursion (Optional)

  4. Introducing Methods Method Structure A method is a collection of statements that are grouped together to perform an operation.

  5. Introducing Methods, cont. • parameter profile refers to the type, order, and number of the parameters of a method. • method signature is the combination of the method name and the parameter profiles. • The parameters defined in the method header are known as formal parameters. • When a method is invoked, its formal parameters are replaced by variables or data, which are referred to as actual parameters.

  6. Declaring Methods public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; }

  7. Calling Methods Example 4.1 Testing the max method This program demonstrates calling a method max to return the largest of the int values TestMax

  8. Calling Methods, cont.

  9. Calling Methods, cont.

  10. CAUTION A return statement is required for a nonvoid method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int xMethod(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; } To fix this problem, delete if (n<0) in the code.

  11. Passing Parameters public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); }

  12. Pass by Value Example 4.2 Testing Pass by value This program demonstrates passing values to the methods. TestPassByValue

  13. Pass by Value, cont.

  14. Overloading Methods Example 4.3 Overloading the max Method public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } TestMethodOverloading

  15. Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error.

  16. Ambiguous Invocation public class AmbiguousOverloading { public static void main(String[] args) { System.out.println(max(1, 2)); } public static double max(int num1, double num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, int num2) { if (num1 > num2) return num1; else return num2; } }

  17. Scope of Local Variables A local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.

  18. Scope of Local Variables, cont. You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.

  19. Scope of Local Variables, cont.

  20. Scope of Local Variables, cont. // Fine with no errors public static void correctMethod() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x += i; } // i is declared again for (int i = 1; i < 10; i++) { y += i; } }

  21. Scope of Local Variables, cont. // With no errors public static void incorrectMethod() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; x += i; } }

  22. Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method.

  23. Benefits of Methods • Write a method once and reuse it anywhere. • Information hiding. Hide the implementation from the user. • Reduce complexity.

  24. The Math Class • Class constants: • PI • E • Class methods: • Trigonometric Methods • Exponent Methods • Rounding Methods • min, max, abs, and random Methods

  25. Trigonometric Methods • sin(double a) • cos(double a) • tan(double a) • acos(double a) • asin(double a) • atan(double a)

  26. Exponent Methods • exp(double a) Returns e raised to the power of a. • log(double a) Returns the natural logarithm of a. • pow(double a, double b) Returns a raised to the power of b. • sqrt(double a) Returns the square root of a.

  27. Rounding Methods • double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. • double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. • double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. • int round(float x) Return (int)Math.floor(x+0.5). • long round(double x) Return (long)Math.floor(x+0.5).

  28. min, max, abs, and random • max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. • abs(a) Returns the absolute value of the parameter. • random() Returns a random double valuein the range [0.0, 1.0).

  29. Example 4.4 Computing Taxes with Methods Example 3.1, “Computing Taxes,” uses if statements to check the filing status and computes the tax based on the filing status. Simplify Example 3.1 using methods.Each filing status has six brackets. The code for computing taxes is nearly same for each filing status except that each filing status has different bracket ranges. For example, the single filer status has six brackets [0, 6000], (6000, 27950], (27950, 67700], (67700, 141250], (141250, 307050], (307050, ), and the married file jointly status has six brackets [0, 12000], (12000, 46700], (46700, 112850], (112850, 171950], (171950, 307050], (307050, ).

  30. Example 4.4 Computing Taxes with Methods The first bracket of each filing status is taxed at 10%, the second 15%, the third 27%, the fourth 30%, the fifth 35%, and the sixth 38.6%. So you can write a method with the brackets as arguments to compute the tax for the filing status. The signature of the method is: public static double computeTax(double income, int r1, int r2, int r3, int r4, int r5) ComputeTaxWithMethod

  31. Example 4.5 Computing Mean and Standard Deviation Generate 10 random numbers and compute the mean and standard deviation ComputeMeanDeviation

  32. Example 4.6 Obtaining Random Characters Write the methods for generating random characters. The program uses these methods to generate 175 random characters between ‘!' and ‘~' and displays 25 characters per line. To find out the characters between ‘!' and ‘~', see Appendix B, “The ASCII Character Set.” RandomCharacter

  33. Example 4.6 Obtaining Random Characters, cont. Appendix B: ASCII Character Set

  34. Case Studies Example 4.7 Displaying Calendars The program reads in the month and year and displays the calendar for a given month of the year. PrintCalendar

  35. Design Diagram

  36. Recursion (Optional) Example 4.8 Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); Factorial(3) = 3 * factorial(2) = 3 * (2 * factorial(1)) = 3 * ( 2 * (1 * factorial(0))) = 3 * ( 2 * ( 1 * 1))) = 3 * ( 2 * 1) = 3 * 2 = 6 ComputeFactorial

  37. Example 4.8 Computing Factorial, cont.

  38. Example 4.8 Computing Factorial, cont.

  39. Fibonacci Numbers Example 4.8 Computing Finonacci Numbers 0 1 1 2 3 5 8 13 21 34 55 89… f0 f1 fib(0) = 0; fib(1) = 1; fib(n) = fib(n-1) + fib(n-2); n>=2 fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0) +fib(1) = 1 + fib(1) = 1 + 1 = 2

  40. Fibonacci Numbers, cont ComputeFibonacci

  41. Fibonnaci Numbers, cont.

  42. Towers of Hanoi Example 4.10 Solving the Towers of Hanoi Problem Solve the towers of Hanoi problem. TowersOfHanoi

  43. Towers of Hanoi, cont.

  44. Exercise 4.11 GCD gcd(2, 3) = 1 gcd(2, 10) = 2 gcd(25, 35) = 5 gcd(205, 301) = 5 gcd(m, n) Approach 1: Brute-force, start from min(n, m) down to 1, to check if a number is common divisor for both m and n, if so, it is the greatest common divisor. Approach 2: Euclid’s algorithm Approach 3: Recursive method

  45. Approach 2: Euclid’s algorithm // Get absolute value of m and n; t1 = Math.abs(m); t2 = Math.abs(n); // r is the remainder of t1 divided by t2; r = t1 % t2; while (r != 0) { t1 = t2; t2 = r; r = t1 % t2; } // When r is 0, t2 is the greatest common divisor between t1 and t2 return t2;

  46. Approach 3: Recursive Method gcd(m, n) = n if m % n = 0; gcd(m, n) = gcd(n, m % n); otherwise;

  47. Selection Statements • Using if and if...else • Nested if Statements • Using switch Statements • Conditional Operator • Repetition Statements • Looping: while, do-while,and for • Nested loops • Using break and continue Chapter 3 Control Statements

  48. Selection Statements • if Statements • switch Statements • Conditional Operators

  49. if Statements if (booleanExpression) { statement(s); } Example: if (i > 0 && i < 10) { System.out.println("i is an " + "integer between 0 and 10"); }

  50. Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style. Wrong

More Related