Defining methods and more arrays

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
8. Arrays 8.1 Using Arrays 8.2 Reference versus Value Again 8.3 Passing Array Arguments and Returning Arrays 8.4 An Example: Simulating Rolls of the Dice.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Java Unit 9: Arrays Declaring and Processing Arrays.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Procedural programming in Java Methods, parameters and return values.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Building java programs, chapter 3 Parameters, Methods and Objects.
Classes - Intermediate
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 07 Title: Methods, part 1 Reference: MalikFarrell, chap 1, Liang Ch 5.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
CSC 211 Java I for loops and arrays.
Computer Organization and Design Pointers, Arrays and Strings in C
User-Written Functions
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Lecture 5: Some more Java!
Lecture 13: More Arrays Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
A Lecture for the c++ Course
JavaScript: Functions.
Java Arrays. Array Object An array :a container object holds a fixed number of values of a single type. The length of an array is established when the.
Methods.
User-Defined Functions
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
CS139 – Fall 2010 How far we have come
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter 8: Collections: Arrays
Building Java Programs Chapter 7
Object Oriented Programming COP3330 / CGS5409
6 Chapter Functions.
Introducing Arrays Array is a data structure that represents a collection of the same types of data.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
METHODS (FUNCTIONS) By: Lohani Adeeb khan.
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
CHAPTER 6 GENERAL-PURPOSE METHODS
IFS410 Advanced Analysis and Design
Chapter 4 Writing Classes.
Chapter 6 Methods.
Building Java Programs
Week 4 Lecture-2 Chapter 6 (Methods).
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Arrays in Java.
Suggested self-checks: Section 7.11 #1-11
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
CMPE212 – Reminders Course Web Site:
In this class, we will cover:
How do you do the following?
Corresponds with Chapter 5
Week 7 - Monday CS 121.
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Defining methods and more arrays 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? Other questions?

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

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

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; }

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

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 }

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

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

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

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

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

The header of a method public static double findMax (double[] myArray) 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 or private

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

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

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; }

System.out.println(sum); public class BasicMath { public static void main(String[] args) { Scanner console = new Scanner (System.in); int x = console.nextInt(); int y = console.nextInt(); } 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; }

System.out.println(sum); public class BasicMath { public static void main(String[] args) { Scanner console = new Scanner (System.in); int x = console.nextInt(); int y = console.nextInt(); } 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; }

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

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”

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() )

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

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

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

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

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]); }

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]); }

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

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?

Copy? Deep copy Shallow copy: int[] x = {1,2,3,4,5}; 1 2 3 4 5 x 1 2 3 4 5 y 1 2 3 4 5 y 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]; } Shallow copy: int[] x = {1,2,3,4,5}; int[] y; y = x;

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

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

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

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

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

79 87 94 82 67 98 87 81 74 91 scores 91 87 94 82 67 98 87 81 74 79 91 74 94 82 67 98 87 81 87 79 91 74 81 82 67 98 87 94 87 79 91 74 81 87 98 67 82 94 87 79 91 74 81 87 67 98 82 94 87 79

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) { swap value in pos. left w. value in pos. right increment left decrement right }

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

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()

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); x 90 ___ 38 70 anArray x 70 ___ 38 90 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 Arrays are objects! We pass a reference, not the value. anArray is a reference to the same object that was passed. x x x x int [] x = {72, 38, 92}; reverse(x); x x 90 ___ 38 70 anArray x 70 ___ 38 90 anArray

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