Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Methods 11/10/2015. Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods.

Similar presentations


Presentation on theme: "Java Methods 11/10/2015. Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods."— Presentation transcript:

1 Java Methods 11/10/2015

2 Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods.

3 Program with static method public class FreshPrince { public static void main(String[] args) { rap(); System.out.println(); rap(); } public static void rap() { System.out.println("Now this is the story all about how"); System.out.println("My life got flipped turned upside-down"); } } Output: Now this is the story all about how My life got flipped turned upside-down Now this is the story all about how My life got flipped turned upside-down

4 Method Syntax [static] ( parameter-list ) { return something } public: It can be called from outside the class. For now we will make them all public. private: Can only be called from within the class. (Later) Default (No modifier) Can be accessed within the class and the package (folder). static You do not need to make an instance of the object to use it. For now our methods will be static. If not defined as static, then it is not static. void: Nothing. Like a procedure int, double, char, int [], String [],Class name (Later): Defines the thing being returned. Start with a lowercase letter, and describes what the method is doing. Everything is a value parameter! (type var, type var, type var) return: Jumps out of the method and returns the answer.

5 Example import java.util.Scanner; // program uses class Scanner public class Addition { // main method begins execution of Java application public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1, number2, sum; System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user sum = total(number1, number2); // add numbers System.out.printf( "Sum is %d\n", sum ); // display sum } // end method main public static int total(int first, int second) { return first+second; } } // end class Addition Can be called from outside the class. Does not need to be instantiated, made into an object, to use. Returns an integer

6 Breaking down the method public static int total(int first, int second) { return first+second; } Can be called from outside the class Can be called without first making an object Returns an integer value Name of the method Parameters/ messages. Everything is a value parameter! Used to return a value from the method and kick out of the method

7 Dry run in your notebook public static void fun(int a, int b) { a+=b; b+=a; } What is the output from the following code int x = 3, y = 5; fun(x, y); System.out.println(x + “ “ + y);

8 Dry run public static int fun2(int x, int y) { y -= x; return y; } What are the values of a and b after the following? int a = 3, b = 7; b = fun(a, b); a = fun(b, a);

9 What does the following method do? public static int process(double amt) { return (int) (amt * 100 + 0.5) % 100; } A) Returns the cent portion of amt. B) Returns the number of whole dollars in amt. C) Returns amt converted to the nearest cent D) Returns amt rounded to the nearest integer E) Returns amt truncated to the nearest integer Order of ops 1)() 2)[], x++, x--, !x, (type casting) 3)*, /, % 4)+, - 5) = 6)==, != 7)&& 8)|| 9)=, +=, -=,

10 Dry run R2 (A2.6). Consider the following method public int change(int value) { if(value < 3) return value % 3; else return value % 3 + 10 * change(value/3); } What will be returned by the call change(45)? A.0 B. 21 C.150 D.500 E.1200

11

12 12 When a method is called, the program's execution... –"jumps" into that method, executing its statements, then –"jumps" back to the point where the method was called. public class MethodsExample { public static void main(String[] args) { message1(); message2(); System.out.println("Done with main."); }... } public static void message1() { System.out.println("This is message1."); } public static void message2() { System.out.println("This is message2."); message1(); System.out.println("Done with message2."); } public static void message1() { System.out.println("This is message1."); } Control flow

13 Style Declare the main method as the first method. Declare other methods later.

14 Stats Pack: Write a program with methods to calculate the following. Factorial –Sent a positive integer, returns its factorial. (Note: 0! = 1) Combinations Write a method that will find the number of combinations of n items taken r at a time. Combinations of n items take r at a time= n!/((r!)(n-r)!) –Enter the values for n and r in the main body –Calculate and return the number of combinations in the method –Show the number of combinations in the main body. Permutations Write a method that will find the number of permutations of n items taken r at a time. Permutations of n items taken r at a time= n!/(n-r)! –Enter the values for n and r in the main body –Calculate and return the number of combinations in the method –Show the number of combinations in the main body.

15 public static void sort(String [] list) { for(int start = 0; start < list.length-1; start++) { int index = start; for(int k = start + 1; k < list.length; k++) { if(list[k].compareTo(list[index]) > 0) index = k; } String temp = list[start]; list[start] = list[index]; list[index] = temp; } Assume the String array words is initialized as shown below. word BillJoeSueAnnMelZeb What will the array word look like after the third pass through the outer loop in the call sort(word)? Note how an array is passed to a method.

16 Insertion Sort // a is the name of the array // nElems stores the number of elements being sorted // This example is for sorting an array of ints int in, out; for(out=1; out<nElems; out++) // out is dividing line { int dummy = a[out]; // dummy Need to modify for sorting different types in = out; // start shifts at out while(in>0 && a[in-1] >= dummy) // until one is smaller, { a[in] = a[in-1]; // Slide: shift item right, in--; // go left one position } a[in] = dummy; // Back: insert marked item } // end for

17 Second Method Program Main Body –Get 9 scores –Call methods –Show results Scores in order Low to High Mean, median Push: Mode, standard deviation Methods –Insertion Sort –Mean –Median –Push: Mode, standard deviation


Download ppt "Java Methods 11/10/2015. Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods."

Similar presentations


Ads by Google