Download presentation
Presentation is loading. Please wait.
Published byRalph Douglas Modified over 8 years ago
1
Copyright 2008 by Pearson Education Java Programing Methods
2
2 Defining Methods A method is a collection of statements that are grouped together to perform an operation.
3
3 Defining Methods A method is a collection of statements that are grouped together to perform an operation.
4
4 Method Signature Method signature is the combination of the method name and the parameter list.
5
5 Formal Parameters The variables defined in the method header are known as formal parameters.
6
6 Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument.
7
7 Return Value Type A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. For example, the returnValueType in the main method is void.
8
8 Testing the max method This program demonstrates calling a method max to return the largest of the int values Calling Methods
9
9 Calling Methods, cont.
10
10 Trace Method Invocation i is now 5
11
11 Trace Method Invocation j is now 2
12
12 Trace Method Invocation invoke max(i, j)
13
13 Trace Method Invocation invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2
14
14 Trace Method Invocation declare variable result
15
15 Trace Method Invocation (num1 > num2) is true since num1 is 5 and num2 is 2
16
16 Trace Method Invocation result is now 5
17
17 Trace Method Invocation return result, which is 5
18
18 Trace Method Invocation return max(i, j) and assign the return value to k
19
19 Trace Method Invocation Execute the print statement
20
Returning a value public static type name ( parameters ) { statements ;... return expression ; } Example: // Returns the slope of the line between the given points. public static double slope(int x1, int y1, int x2, int y2) { double dy = y2 - y1; double dx = x2 - x1; return dy / dx; }
21
Return examples // Converts Fahrenheit to Celsius. public static double fToC(double degreesF) { double degreesC = 5.0 / 9.0 * (degreesF - 32); return degreesC; } // Computes triangle hypotenuse length given its side lengths. public static double hypotenuse(int a, int b) { double c = Math.sqrt(a * a + b * b); return c; } You can shorten the examples by returning an expression: public static double fToC(double degreesF) { return 5.0 / 9.0 * (degreesF - 32); }…,,,
22
Fixing the common error Instead, returning sends the variable's value back. The returned value must be stored into a variable or used in an expression to be useful to the caller. public static void main(String[] args) { double s = slope(0, 0, 6, 3); System.out.println("The slope is " + s); } public static double slope(int x1, int x2, int y1, int y2) { double dy = y2 - y1; double dx = x2 - x1; double result = dy / dx; return result; }
23
System.out.printf an advanced command for printing formatted text System.out.printf(" format string ", parameters ); A format string contains placeholders to insert parameters into it: %d an integer %f a real number %s a string Example: int x = 3; int y = 2; System.out.printf("(%d, %d)\n", x, y); // (3, 2)
24
24 CAUTION A return statement is required for a value-returning method. The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value. To fix this problem, delete if (n < 0) in (a), so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated.
25
25 Reuse Methods from Other Classes NOTE: One of the benefits of methods is for reuse. The max method can be invoked from any class besides TestMax. If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max).
26
Reuse Methods from Other Classes The easiest way to call a method is to declare it as public static In the same class call the method using its name In another class, call the method as classname.methodName 26 class A { public static void m1() { System.out.println(“Hello 2”); } public static void main (String [ ] arg ) { System.out.println(“Hello 1”); m1(); System.out.println(“Hello 3”); } } class B { public static void main (String [ ] arg ) { System.out.println(“Hello 1”); A.m1(); System.out.println(“Hello 3”); } }
27
27 Call Stacks
28
28 Method Overloading Method overloading Several methods of the same name Different parameter set for each method Number of parameters Parameter types
29
29 Method Overloading A class may define multiple methods with the same name---this is called method overloading usually perform the same task on different data types Example: The PrintStream class defines multiple println methods, i.e., println is overloaded: println (String s) println (int i) println (double d) … The following lines use the System.out.print method for different data types: System.out.println ("The total is:"); double total = 0; System.out.println (total);
30
Method Overloading double tryMe (int x) { return x +.375; } Version 1 double tryMe (int x, double y) { return x * y; } Version 2 result = tryMe (25, 4.32)Invocation
31
More Examples double tryMe ( int x ) { return x + 5; } double tryMe ( double x ) { return x *.375; } double tryMe (double x, int y) { return x + y; } tryMe( 1 ); tryMe( 1.0 ); tryMe( 1.0, 2); tryMe( 1, 2); tryMe( 1.0, 2.0); Which tryMe will be called?
32
32 Recursion Recursive method Calls itself (directly or indirectly) through another method Method knows how to solve only a base case Method divides problem Base case Simpler problem Method now divides simpler problem until solvable Recursive call Recursive step
33
33 Example Using Recursion: The Fibonacci Series Fibonacci series Each number in the series is sum of two previous numbers e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21… fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 1 ) fibonacci(0) and fibonacci(1) are base cases Golden ratio (golden mean)
34
34 Passing Parameters public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using nPrintln(“Welcome to Java”, 5); What is the output? Suppose you invoke the method using nPrintln(“Computer Science”, 15); What is the output? Can you invoke the method using nPrintln(15, “Computer Science”);
35
When you invoke a method with an argument, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method. 35 Pass by Value
36
36 Pass by Value…
37
Array parameter example public static void main(String[] args) { int[] iq = {126, 84, 149, 167, 95}; double avg = average(iq); System.out.println("Average = " + avg); } public static double average(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) { sum += array[i]; } return (double) sum / array.length; } Output: Average = 124.2
38
Arrays passed by reference Arrays are objects. When passed as parameters, they are passed by reference. (Changes made in the method are also seen by the caller.) Example: public static void main(String[] args) { int[] iq = {126, 167, 95}; doubleAll(iq); System.out.println(Arrays.toString(iq)); } public static void doubleAll(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = a[i] * 2; } } Output: [252, 334, 190] index012 value12616795 index012 value252334190 iq a
39
Arrays as return (declaring) public static type [] methodName ( parameters ) { Example: public static int[] countDigits(int n) { int[] counts = new int[10]; while (n > 0) { int digit = n % 10; n = n / 10; counts[digit]++; } return counts; }
40
Arrays as return (calling) type [] name = methodName ( parameters ); Example: public static void main(String[] args) { int[] tally = countDigits(229231007); System.out.println(Arrays.toString(tally)); } Output: [2, 1, 3, 1, 0, 0, 0, 1, 0, 1]
41
Array param/return question Modify our previous Sections program to use static methods that use arrays as parameters and returns. Sections attended: [9, 6, 7, 4, 3] Student scores: [20, 18, 20, 12, 9] Student grades: [100.0, 90.0, 100.0, 60.0, 45.0] Sections attended: [6, 7, 5, 6, 4] Student scores: [18, 20, 15, 18, 12] Student grades: [90.0, 100.0, 75.0, 90.0, 60.0] Sections attended: [5, 6, 5, 7, 6] Student scores: [15, 18, 15, 20, 18] Student grades: [75.0, 90.0, 75.0, 100.0, 90.0]
42
Example Create circle class that consists of the circle radius with methods to initialize the radius, calculate the circumference of the circle, and calculate the area of the circle.
43
Example Create a class Time that contains data members, hour, minute, second to store the time value, and sets hour, minute, second to zero, provide three methods for converting time to ( 24 hour ) and another one for converting time to (12 hour) and a function that sets the time to a certain value specified by three parameters
44
44 Example Write a 12-hour clock program that declares a clock class to store hours, minutes, seconds, A.M. and P.M. provide methods to perform the following tasks: Set hours, minutes, seconds to 00:00:00 by default Initialize hours, minutes, seconds, A.M. and P.M. from user entries Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12-hour clock value of AM or PM Display the time in hours:minutes:seconds AM / PM format
45
Find the output 45 int i = 1, j = 1, val; while (i < 25){ System.out.println(j + " "); val = i + j; j = i; i = val; }
46
Find the output int val; for (val = -5; val <= 5; val++) { switch (val) { case 0: System.out.println ("India"); break; } if (val > 0) System.out.println ("B"); else if (val < 0) System.out.println("X"); } 46
47
Program Create class account to save personal account for a bank with interest. The class has account# and balance data The class has operations: deposit, withdraw, interest_earned {2% interest will be credited to account at end of each month if balance exceeds $10,000} and display_data 47
48
Arrays array: object that stores many values of the same type. element: One value in an array. index: A 0-based integer to access an element from an array. index0123456789 value1249-226517-684723 element 0element 4element 9
49
Array declaration type [] name = new type [ length ]; Example: int[] numbers = new int[10]; index0123456789 value0000000000
50
Array declaration, cont. The length can be any integer expression. int x = 2 * 3 + 1; int[] data = new int[x % 5 + 2]; Each element initially gets a "zero-equivalent" value. TypeDefault value int0 double0.0 booleanfalse String or other object null (means, "no object")
51
What happens if … Valid code: int k=7; long[] primes = new long[k]; Invalid Code: int k; long[] primes =new long[k]; Compilation Output: MorePrimes.java:6: variable k might not have been initialized long[] primes = new long[k]; ^
52
Accessing elements name [ index ]// access name [ index ] = value ;// modify Example: numbers[0] = 27; numbers[3] = -6; System.out.println(numbers[0]); if (numbers[3] < 0) { System.out.println("Element 3 is negative."); } index0123456789 value0000000000 index0123456789 value2700-6000000
53
Arrays of other types double[] results = new double[5]; results[2] = 3.4; results[4] = -0.5; boolean[] tests = new boolean[6]; tests[3] = true; index01234 value0.0 3.40.0-0.5 index012345 valuefalse truefalse
54
Out-of-bounds Legal indexes: between 0 and the array's length - 1. Reading or writing any index outside this range will throw an ArrayIndexOutOfBoundsException. Example: int[] data = new int[10]; System.out.println(data[0]); // okay System.out.println(data[9]); // okay System.out.println(data[-1]); // exception System.out.println(data[10]); // exception index0123456789 value0000000000
55
Accessing array elements int[] numbers = new int[8]; numbers[1] = 3; numbers[4] = 99; numbers[6] = 2; int x = numbers[1]; numbers[x] = 42; numbers[numbers[6]] = 11; // use numbers[6] as index x numbers x3 index0123456789 value index0123456789 value0411429902000
56
Arrays and for loops It is common to use for loops to access array elements. for (int i = 0; i < 8; i++) { System.out.print(numbers[i] + " "); } System.out.println(); // output: 0 4 11 0 44 0 0 2 Sometimes we assign each element a value in a loop. for (int i = 0; i < 8; i++) { numbers[i] = 2 * i; } index01234567 value02468101214
57
The length field An array's length field stores its number of elements. name.length for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } // output: 0 2 4 6 8 10 12 14 It does not use parentheses like a String's.length(). What expressions refer to: The last element of any array? The middle element?
58
Weather question Use an array to solve the weather problem: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44.6 4 days were above average.
59
Weather answer // Reads temperatures from the user, computes average and # days above average. import java.util.*; public class Weather { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("How many days' temperatures? "); int days = console.nextInt(); int[] temperatures = new int[days]; // array to store days' temperatures int sum = 0; for (int i = 0; i < days; i++) { // read/store each day's temperature System.out.print("Day " + (i + 1) + "'s high temp: "); temperatures[i] = console.nextInt(); sum += temperatures[i]; } double average = (double) sum / days; int count = 0; // see if each day is above average for (int i = 0; i < days; i++) { if (temperatures[i] > average) { count++; } // report results System.out.printf("Average temp = %.1f\n", average); System.out.println(count + " days above average"); }
60
A multi-counter problem Problem: Examine a large integer and count the number of occurrences of every digit from 0 through 9. Example: The number 229231007 contains: two 0s, one 1, three 2s, one 7, and one 9. We could declare 10 counter variables for this... int counter0, counter1, counter2, counter3, counter4, counter5, counter6, counter7, counter8, counter9; Yuck!
61
A multi-counter problem A better solution is to use an array of size 10. The element at index i will store the counter for digit value i. for integer value 229231007, our array should store: The index at which a value is stored has meaning. Sometimes it doesn't matter. What about the weather case? index0123456789 value2130000101
62
Creating an array of tallies int num = 229231007; int[] counts = new int[10]; while (num > 0) { // pluck off a digit and add to proper counter int digit = num % 10; counts[digit]++; num = num / 10; } index0123456789 value2130000101
63
Array histogram question Given a file of integer exam scores, such as: 82 66 79 63 83 Write a program that will print a histogram of stars indicating the number of students who earned each unique exam score. 85: ***** 86: ************ 87: *** 88: * 91: ****
64
Histogram variations Curve the scores; add a fixed number to each score. (But don't allow a curved score to exceed the max of 101.) Chart the data with a DrawingPanel. window is 100px tall 2px between each bar 10px tall bar for each student who earned that score
65
Array histogram answer // Reads an input file of test scores (integers) and displays a // graphical histogram of the score distribution. import java.awt.*; import java.io.*; import java.util.*; public class Histogram { public static final int CURVE = 5; // adjustment to each exam score public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("midterm.txt")); int[] counts = new int[101]; // counters of test scores 0 - 100 while (input.hasNextInt()) { // read file into counts array int score = input.nextInt(); score = Math.min(score + CURVE, 100); // curve the exam score counts[score]++; // if score is 87, then counts[87]++ } for (int i = 0; i < counts.length; i++) { // print star histogram if (counts[i] > 0) { System.out.print(i + ": "); for (int j = 0; j < counts[i]; j++) { System.out.print("*"); } System.out.println(); }...
66
Array histogram solution 2... // use a DrawingPanel to draw the histogram DrawingPanel p = new DrawingPanel(counts.length * 3 + 6, 200); Graphics g = p.getGraphics(); g.setColor(Color.BLACK); for (int i = 0; i < counts.length; i++) { g.drawLine(i * 3 + 3, 175, i * 3 + 3, 175 - 5 * counts[i]); }
67
Arrays of Arrays Two-Dimensional arrays float[][] temperature=new float[10][365]; 10 arrays each having 365 elements First index: specifies array (row) Second Index: specifies element in that array (column) In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
68
Initializing Array of Arrays int[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61, 74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87, 94}, {43, 98, 78, 56, 99} }; //5 arrays with 5 elements each
69
Arrays of Arrays of Varying Length All arrays do not have to be of the same length float[][] samples; samples=new float[6][];//defines # of arrays samples[2]=new float[6]; samples[5]=new float[101]; Not required to define all arrays
70
Initializing Varying Size Arrays int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } }; //Three arrays //First array has 3 elements //Second array has 2 elements //Third array has 5 elements
71
71 SOME USEFUL ARRAY OPERATIONS Finding the Average of the Values in a Numeric Array To find the average of the values in a numeric array, first find the sum of the values in the array. Then divide this sum by the number of elements in the array.
72
Examples Using Arrays Using arrays to analyze survey results 40 students rate the quality of food 1-10 Rating scale: 1 mean awful, 10 means excellent Place 40 responses in array of integers Summarize results
73
Sorting Arrays Sorting data Attracted intense research in computer-science field Bubble sort Smaller values “bubble” their way to top of array Larger values “sink” to bottom of array Use nested loops to make several passes through array Each pass compares successive pairs of elements Pairs are left along if increasing order (or equal) Pairs are swapped if decreasing order
74
Searching Arrays: Linear Search and Binary Search Searching Finding elements in large amounts of data Determine whether array contains value matching key value Linear searching Binary searching
75
Searching Arrays: Linear Search and Binary Search Linear search Compare each array element with search key If search key found, return element index If search key not found, return –1 (invalid index) Works best for small or unsorted arrays Inefficient for larger arrays
76
Searching Arrays: Linear Search and Binary Search Binary search Efficient for large, sorted arrays Eliminates half of the elements in search through each pass Compare middle array element to search key If element equals key Return array index If element is less than key Repeat search on first half of array If element is greater then key Repeat search on second half of array Continue search until element equals search key (success) Search contains one element not equal to key (failure)
77
Multidimensional Arrays A farmer has 10 farms of beans each in 5 countries, and each farm has 30 fields! Three-dimensional array long[][][] beans=new long[5][10][30]; //beans[country][farm][fields]
78
Input/output (I/O) import java.io.*; Create a File object to get info about a file on disk. (This doesn't actually create a new file on the hard disk.) File f = new File("example.txt"); if (f.exists() && f.length() > 1000) { f.delete(); } Method nameDescription canRead() returns whether file is able to be read delete() removes file from disk exists() whether this file exists on disk getName() returns file's name length() returns number of bytes in file renameTo( file ) changes name of file
79
Output to files PrintStream : An object in the java.io package that lets you print output to a destination such as a file. Any methods you have used on System.out (such as print, println ) will work on a PrintStream. Syntax: PrintStream name = new PrintStream(new File(" file name ")); Example: PrintStream output = new PrintStream(new File("out.txt")); output.println("Hello, file!"); output.println("This is a second line of output.");
80
Details about PrintStream PrintStream name = new PrintStream(new File(" file name ")); If the given file does not exist, it is created. If the given file already exists, it is overwritten. The output you print appears in a file, not on the console. You will have to open the file with an editor to see it. Do not open the same file for both reading ( Scanner ) and writing ( PrintStream ) at the same time. You will overwrite your input file with an empty file (0 bytes).
81
System.out and PrintStream The console output object, System.out, is a PrintStream. PrintStream out1 = System.out; PrintStream out2 = new PrintStream(new File("data.txt")); out1.println("Hello, console!"); // goes to console out2.println("Hello, file!"); // goes to file A reference to it can be stored in a PrintStream variable. Printing to that variable causes console output to appear. You can pass System.out as a parameter to a method expecting a PrintStream. Allows methods that can send output to the console or a file.
82
Reading files To read a file, pass a File when constructing a Scanner. Scanner name = new Scanner(new File(" file name ")); Example: File file = new File("mydata.txt"); Scanner input = new Scanner(file); or, better yet: Scanner input = new Scanner(new File("mydata.txt"));
83
Prompting for a file name We can ask the user to tell us the file to read. The file name might have spaces; use nextLine(), not next() // prompt for input file name Scanner console = new Scanner(System.in); System.out.print("Type a file name to use: "); String filename = console.nextLine(); Scanner input = new Scanner(new File(filename)); What if the user types a file name that does not exist?
84
Compiler error w/ files The following program does not compile: import java.io.*; // for File import java.util.*; // for Scanner public class ReadFile { public static void main(String[] args) { Scanner input = new Scanner(new File("data.txt")); String text = input.next(); System.out.println(text); } The following error occurs: ReadFile.java:6: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown Scanner input = new Scanner(new File("data.txt")); ^
85
Testing for valid input Scanner methods to see what the next token will be: These methods do not consume input; they just give information about the next token. Useful to see what input is coming, and to avoid crashes. MethodDescription hasNext() returns true if there are any more tokens of input to read (always true for console input) hasNextInt() returns true if there is a next token and it can be read as an int hasNextDouble( ) returns true if there is a next token and it can be read as a double
86
Using hasNext methods To avoid exceptions: Scanner console = new Scanner(System.in); System.out.print("How old are you? "); if (console.hasNextInt()) { int age = console.nextInt(); // will not crash! System.out.println("Wow, " + age + " is old!"); } else { System.out.println("You didn't type an integer."); } To detect the end of a file: Scanner input = new Scanner(new File("example.txt")); while (input.hasNext()) { String token = input.next(); // will not crash! System.out.println("token: " + token); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.