1 / 46

CSC 211 Java I

CSC 211 Java I. Defining methods and more arrays. Today’s plan. Q&A on the assignment Defining methods More about arrays. Questions on the assignment. How do you find the maximum element in an array? What about the index of that element? How do you exclude the minimum and maximum scores?

cearls
Télécharger la présentation

CSC 211 Java I

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. CSC 211 Java I Defining methods and more arrays

  2. Today’s plan • Q&A on the assignment • Defining methods • More about arrays

  3. Questions on the assignment • How do you find the maximum element in an array? • What about the index of that element? • How do you exclude the minimum and maximum scores? • Other questions?

  4. Today’s plan • Q&A on the assignment • Defining methods • More about arrays

  5. Being proactive • In the last homework we had to find the maximum of an array • We might want to do this again • We might need to do it more than once in our program (for example, three times!) • It is a “self contained” operation, easily described: • Input: An array of doubles • Output: A double that is the maximum in the array

  6. Being proactive double myMax = myArray [0]; for (int j = 1; j < myArray.length; j++) { if (myArray[j] > max) { myMax = myArray[j]; } } public static double findMax (double[] myArray) { return myMax; }

  7. Methods • A method is a collection of programming statements devoted to performing a clearly specified part of the program’s objective • Ie: a collection of statement that carries out a very specific function • E.g. Given an array, find the highest value

  8. Writing a method (sneak preview): public static double findMax(double[] arr) { ..... } • Begin with a method header that includes • The “visibility” - for now we will use ‘public’ • ‘static’ -- again, more on this later • The “return type” : • ie the type of data returned by the array such as a double • If the array does not return a value, we say ‘void’ • The identifier (name) given to the method • The statements of the method are enclosed by braces { and }

  9. Example public class SampleHw6 { public static void main(String[] args) { …… double max; max = findMax(scores); …… } public static double findMax (double[] myArray) { …… } }

  10. Methods • When a method is invoked (by calling its name) the flow of control (i.e. the order in which the program is executing) is transferred to that group of statements • When the method’s execution is completed, the flow returns to the location from which the method was originally called • A method terminates in one of two ways: • the end of the method is reached i.e. ‘ } ’ • by a return statement

  11. Example: Tracing the Flow public class SampleHw6 { public static void main(String[] args) { …… double max = findMax(scores); …… } public static double findMax (double[] myArray) { …… return myMax; } } 1 2

  12. Methods that return a value • It is common for methods to actually compute something and RETURN the result of that computation • If a method returns a result, the data type returned of that result MUST be specified in the header (the opening line). • Can be any data type such as a int, char, double, boolean, String, Triangle, Square, etc • If the method does not returning anything, the return type is specified as void

  13. The return type of a method public static void main (String[] args) public static int add ( ) public static double myMethod ( ) public static String[] yourMethod ( )

  14. VISIBILITY MODIFIERS The full significance of this modifier is beyond the scope of CSC 211. The basics: When your program consists of a single class, the main method is declared as public. Methods other than main() may be either public orprivate The header of a method public static double findMax (double[] myArray)

  15. STATIC MODIFIERS The full significance of this modifier is beyond the scope of CSC 211. Essential things to know: When your program consists of a single class, the main method and all the service methods must be declared static The header of a method public static double findMax (double[] myArray)

  16. VISIBILITY AND STATIC MODIFIERS Magic words for now RETURN TYPE Tells us what data-type is returned by this method (if any) after its execution If the method does not return a value, the return type is called: void The return type can be any of our familiar primitive data types or an object of a particular class (String, Triangle, Square, etc) The header of a method public static double findMax (double[] myArray)

  17. NAME OF METHOD Identifier chosen by the programmer who wrote the method. By convention it should start with a lower case. Initials of words after the first one in the identifier (if any) should be capitalized VISIBILITY AND STATIC MODIFIERS RETURN TYPE The header of a method public static double findMax (double[] scores)

  18. VISIBILITY AND STATIC MODIFIERS PARAMETERS Data needed (if any) by the method. Note: Many methods do NOT take any parameters at all. RETURN TYPE NAME OF METHOD The header of a method public static double findMax (double[] myArray)

  19. Try It: Write the header described by the comment below. public class BasicMath { … //create a method called ‘add’ that //accepts 2 integers and returns their sum

  20. Example: public class BasicMath { … //create a method called ‘add’ that //accepts 2 integers and returns their sum public static int add (int num1, int num2) { int result = num1 + num2; return result; }

  21. public static void main(String[] args) { Scanner console = new Scanner (System.in); int x = console.nextInt(); int y = console.nextInt(); } public class BasicMath { A method call with parameters causes IMPLICIT ASSIGNMENT STATEMENTS to be executed, assigning the values of the actual parameters to the formal parameters listed in the method code: num1 = x; num2 = y; int sum = add (x,y); System.out.println(sum); public static int add (int num1, int num2) { int result = num1 + num2; return result; }

  22. public static void main(String[] args) { Scanner console = new Scanner (System.in); int x = console.nextInt(); int y = console.nextInt(); } public class BasicMath { With a method that returns a value, (i.e. not a void method), it is often the case that the method call is part of an ASSIGNMENT STATEMENT as seen here. Once flow of control returns following execution of the method, that assignment statement will be executed. The returned value of the method is then used in the assignment statement. int sum = add (x,y); result System.out.println(sum); public static int add (int num1, int num2) { int result = num1 + num2; return result; }

  23. Get to work • Complete Parts 1.1 – 1.4 on the lab • It involves writing several methods • You must also write a main method to call the methods you have created

  24. Sharing variables • In all the examples you have worked out so far no two methods shared any variable • Sometimes you DO want two separate methods to work on the same variables that are used throughout the program • This should rarely be used. Ie: Avoid if at all possible. If they come up, I will tell you the situations where it is acceptable. • We are talking about this now mostly as preparation for CSC 212 … • This is an issue of something called “SCOPE”

  25. Scope • The scope of a variable is the area in which that variable can be used (referenced) • A variable can be declared: • Inside a method or a construct • At class level (not inside a method – including main() )

  26. Data scope • A variable declared at class level, meaning outside of any method (including main), can be used by every single method in that class • A variable declared inside of a method or construct (loop, if statement, etc), can be only be used inside that method or construct. • These are known as “local variables” • Their existence is LOCAL to the method or construct in which they are declared • Outside of the method/construct, it’s as if the variable does not exist

  27. What’s your scope • Complete Part 2.1 and 2.2 in the lab

  28. A word on STATIC • If your program consists of a single class, all methods should be declared static • In this situation, every variable declared at class level MUST be declared static • More explanation in 212

  29. Today’s plan • Q&A on the assignment • Defining methods • More about arrays

  30. Are you with me? • Will this code compile? int[] numbers = new int[4]; for (int i = 0; i <= numbers.length; i++) { System.out.println(numbers[i]); }

  31. Are you with me? • Will this code run successfully? int[] numbers = new int[4]; for (int i = 0; i <= numbers.length; i++) { System.out.println(numbers[i]); }

  32. More Arrays: Bounds checking • Once an array is created, it has a fixed size (for example 10). • An index used in an array reference must specify a valid element: the index value must be in bounds (0 to 9) • The Java interpreter will complain if an array index is out of bounds . Notice that the compiler will NOT complain • This is called automatic bounds checking

  33. Copying an array • Suppose x is an array of int,that has been instantiated as follows: • int[] x = {1,2,3,4,5}; • Suppose we want to make a copy of it • What do we do? • What does “make a copy” really mean?

  34. Copy? 1 2 3 4 5 • Shallow copy: int[] x = {1,2,3,4,5}; int[] y; y = x; • Deep copy int[] x = {1,2,3,4,5}; int[] y = new int[5]; for (int i = 0; i < x.length; i++) {y[i] = x[i]; } x x 1 2 3 4 5 1 2 3 4 5 y y

  35. Copying an array • Complete Part 3.1 – 3.3 on the lab • You need to write several methods that copy arrays and a main method that tests the methods you have written

  36. scores[0] 90 ______ 30 ______ 70 scores[1] scores[0] 70 ______ 30 ______ 90 scores[2] scores[1] scores[2] Swapping values in array How would you swap the 1st and 3rd element?

  37. scores[0] 90 ______ 30 ______ 90 90 scores[1] scores[0] 70 ______ 30 ______ 90 90 scores[2] scores[1] scores[2] Swapping values in array scores[0] = scores[2]; scores[2] = scores[0];

  38. scores[0] 90 ______ 30 ______ 70 90 70 scores[1] scores[0] 70 ______ 30 ______ 90 70 scores[2] scores[1] scores[2] Swapping values in array temp = scores[0]; scores[0] = scores[2]; scores[2] = temp;

  39. scores 0 1 2 3 4 5 6 7 8 9 scores 0 1 2 3 4 5 6 7 8 9 79 87 94 82 67 98 87 81 74 91 91 74 81 87 98 67 82 94 87 79 Reversing an array

  40. 79 87 94 82 67 98 87 81 74 91 91 87 94 82 67 98 87 81 74 79 9174 94 82 67 98 87 81 87 79 917481 82 67 98 87 9487 79 91748187 67 98 829487 79 9174818798 67829487 79 scores

  41. Reversing an array in JEnglish Initialize some variable (e.g. left ) to the index of the first element in the array: (0); Initialize another variable (e.g.right)to the index of the last element in the array: (length-1) while (left < right) { swapvalue in pos. left w. value in pos. right increment left decrement right }

  42. Get your hands dirty • Complete Parts 3.4 and 3.5 on the lab • You need to implement and test the algorithm for reversing an array we just discussed

  43. Implementation: A method to reverse an array public static void reverse(int[] anArray) { int temp; int left = 0; int right = anArray.length – 1; while (left < right) { temp = anArray[left]; anArray[left] = anArray[right]; anArray[right] = temp; left++; right--; } } //end method reverse()

  44. 70 ___ 38 ___ 90 90 ___ 38 ___ 70 x x anArray anArray Reference Arrays are objects! *** We pass a reference to the array - NOT THE VALUES of that array. ***In the function we wrote on the previous slide, the parameter, anArray is a reference (i.e. an address) to the array object that was passed when the reverse() method was invoked. int [] x = {72, 38, 92}; reverse(x);

  45. 70 ___ 38 ___ 90 90 ___ 38 ___ 70 x x anArray anArray public static void reverse(int [] anArray){ int temp; int left = 0; int right = anArray.length – 1; while (left < right) { temp = anArray[left]; anArray[left++] = anArray[right]; anArray[right--} = temp;} } x Reference x x x x Arrays are objects! We pass a reference, not the value.anArray is a reference to the same object that was passed. int [] x = {72, 38, 92}; reverse(x); x

  46. Get your hands dirty • Complete Parts 3.6 and 3.7 on the lab • You need to write methods that determines if two arrays have exactly the same values in the same order and a program that tests your methods

More Related