







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Material Type: Notes; Professor: Thornton; Class: Fund Software Dsgn; Subject: Computing and Information Sciences; University: Kansas State University; Term: Spring 2010;
Typology: Study notes
1 / 13
This page cannot be seen from the preview
Don't miss anything!
Why Write Methods? Many times when we are writing programs we find that we want to repeat the same set of actions multiple times. When we put all the code in a single Main method, we must just write the same lines of code over and over. This leads to programs that are longer than they need to be and “ugly” code.
A method is a section of code that does a particular job. When we want to execute those lines of code, we call the method. This means that instead of repeating a bunch of lines of code when we want to perform an action, we just need to include one line to call the appropriate method. This makes our code much easier to read.
Declaring a Method This section will discuss the format for declaring a method. All methods must have a return type (if the method is performing a calculation and giving back a result), a name , and a number of parameters (pieces of data that the method needs to perform its calculations).
Syntax Methods are declared inside the brackets for the class, but outside the brackets for the main method. For example:
public class Example { public static void main(String[] args) {
}
//Declare method here
//Can declare as many methods as you want }
Here is the syntax for declaring a method:
public static returnType name(params) { //code for method goes here }
For now, don’t worry about what the public static part means – just put that at the beginning of all your methods.
Next, the returnType is the type of data you want this method to give back. For example, if we were writing a method that computed the area of a square with integer sides, then we would
want to return an int – the data type of the area. If you do not want your method to give back a result, then the return type should be void.
The name of method should be descriptive of what the method is doing. For example, a method that computes the area of a square should be called something like area or areaSquare. The rules for naming methods are the same as the rules for naming variables: method names can be made up of letters, numbers, and underscores, but they cannot start with a number.
Finally, the params are a comma-separated list of values that the method needs to do its calculations. Each parameter is listed with a data type and a name. If the method does not need any values to do its calculations, then the params section is left off the method declaration (but the () at the end of the method is still there).
Examples Suppose we want to write a method that computes and returns the area of a rectangle. First, let’s think about what information this method needs to do its computation – these will be the parameters. To compute the area of a rectangle, we need its width and its height. Next, we need to determine the data type of these values. We know that the width and height will be numbers, but they can be either ints or doubles – depending on what kind of values we want to allow. We’ll be more general and make them doubles.
Next, we need to consider what kind of value we’re computing. We want to return the area of a rectangle. Each side of the rectangle is a double, and so the area (and return type) should also be a double.
Here is the declaration for the method that will compute the area of a rectangle:
// This method returns the area of the rectangle with // length length and width width public static double area(double length, double width) {
}
As a second example, suppose we want to write a method that prints all of the values in an array of integers. This method needs to take in the integer array as a parameter, but it doesn’t need to return anything (so it will have a void return type). Here is the declaration:
//This method prints every value in the nums array public static void printArray(int[] nums) {
}
Finally, suppose we want to write a method that returns the number of times a particular character appears in a string. This method needs to take the string we’re examining and the letter
Scanner s = new Scanner(System.in);
for (int i = 0; i < n; i++) { System.out.print(“Enter an integer: “); int val = Integer.parseInt(s.nextLine()); sum += val; }
System.out.println(“The sum is: “ + sum); }
Methods that Return a Value Methods that return a value look fairly similar to void methods. The only difference is that methods that return a value must have the statement:
return expression;
where expression is either the name of a variable, some expression (a math operation, for example), or a constant value (like 4, true, or “hello”). Furthermore, expression should have the same data type as the return type for the method.
Recall the method declaration for computing the area of a rectangle:
// This method returns the area of the rectangle with // length length and width width public static double area(double length, double width) {
}
The formula for the area of a rectangle is the length times the width, so the completed method looks like this:
// This method returns the area of the rectangle with // length length and width width public static double area(double length, double width) { return length*width; }
Notice that length*width is an expression whose data type evaluates to a double – the same type as the return type.
Next, recall the method declaration for counting the occurrences of a character in a string:
//This method returns the number of times letter appears in str public static int countLetter(String str, char letter) {
To implement this method, we will have to loop through all the characters in str, and add one to a count variable every time a character matches letter. After we have finished looping through the string, we will return our count (which should have an int data type). Here is the implementation:
//This method returns the number of times letter appears in str public static int countLetter(String str, char letter) { int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == letter) count++; }
return count; }
Finally, suppose we want to write a method that determines whether or not a particular letter is a character in a string. This method will again need to take the string and the character as parameters. Since it is computing whether or not something is true, its return type should be a boolean. Here is the complete method:
//This method returns true if letter is in str , and false otherwise public static boolean containsLetter(String str, char letter) { bool foundIt = false; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == letter) foundIt = true; }
return foundIt; }
This method is not as efficient as it could be, though. Suppose the first character in str matches letter – do we really need to look through the rest of the string? Here is an optimized version of the same method:
//This method returns true if letter is in str , and false otherwise public static bool containsLetter(String str, char letter) { for (int i = 0; i < str.length(); i++) { //We’ve found it – no need to continue looking if (str.charAt(i) == letter) return true; }
//We must not have found it, or we would have already returned return false; }
The above method is correct. If num1 equals num2, we return true. If num1 does not equal num2, we return false. Those are the only possible scenarios, and each of them has a return statement. We also don’t try to do anything else after returning a value.
Calling Methods Now that we can write separate methods, we need to be able to call them (tell the compiler that we want to execute the code in the method). Suppose our program looks like this, which includes some of the methods written above and some new ones:
public class Methods { public static void main(String[] args) { //The code we write in this section goes here }
//This method prints every value in the nums array public static void printArray(int[] nums) { for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } }
//This method returns the number of times letter appears in str public static int countLetter(String str, char letter) { int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == letter) count++; }
return count; }
// This method returns the area of the rectangle with // length length and width width public static double area(double length, double width) { return length*width; }
//This method asks the user for 10 numbers, //and prints the sum of those numbers public static void sum10() { int sum = 0; Scanner s = new Scanner(System.in);
for (int i = 0; i < n; i++) {
System.out.print(“Enter an integer: “); int val = Integer.parseInt(s.nextLine()); sum += val; }
System.out.println(“The sum is: “ + sum); } }
Calling a Void Method Here is the syntax for calling a method with a void return type:
ClassName.methodName(params);
Here, ClassName is the name of the class that we’re using, and methodName is the name of the method that we want to run. Finally, params is a comma-separated list of values that you want to pass to the method. Each value can be a variable name, a constant value, or an expression (like a math operation). You do not list the type of the parameters when you call the method, but their types should match the parameter types in the method declaration.
Suppose we are inside the main method in the Methods class above. Let’s say we want to call the printArray method. First, we create an array of integers:
//creates space for the array and initializes the values int[] vals = {1, 2, 3, 4};
Now, we are ready to call the printArray method. Here’s how:
Methods.printArray(vals);
Notice that we just list “vals” as the name of the parameter. This variable has the same type as the parameter in the printArray method declaration – an int[].
When we call the printArray method, we pass the vals array. The printArray parameter is named nums, so nums gets initialized to be this vals array. When we print the elements in nums inside the method, it is really printing the elements from vals.
Suppose we are still inside the main method in the Methods class, and that we now want to call the sum10 method. Here’s how:
Methods.sum10();
This method does not take any parameters, but we still end the method call with (). Now, our entire main method looks like this:
When we call countLetter, we pass the value for the word inputted by the user (which gets stored in the str parameter variable) and the value for the character inputted by the user (which gets stored in the letter parameter variable). The method returns the number of times that letter appears in the string, and this result gets stored in the numTimes variable.
How Parameters Work Up until this point, we have glossed over exactly what happens when we pass parameters to methods.
Suppose our full program looked like this:
using System; public class TestParams { public static void main(String[] args) { int val = 4; TestParams.addOne(val); System.out.println(val);
int[] array = {1, 2, 3}; TestParams.zeroArray(array); for (int x : array) { System.out.println(x); } }
public static void addOne(int num) { num++; }
public static void zeroArray(int[] arr) { for (int i = 0; i < arr.length; i++) { arr[i] = 0; } } }
It turns out that when we pass parameters that are ints, doubles, chars, or bools, then they are passed by value. This means that when we do something like:
TestParams.addOne(val);
Then the VALUE of val is passed – not val itself. This means that the value 4 is passed, and so the num parameter in the addOne method gets set to 4. We then add one to the num parameter, so that it has the value 5. When we finish executing this method, we return back to the main method after the call to addOne. At this point, we print out the value of val. This
print statement will print out 4. Even though we added one to num in addOne, num IS NOT val – it was just initialized to have the same value that val did.
On the other hand, arrays (and later objects ) are passed by reference. This means that when we do something like this:
TestParams.zeroArray(array);
Then what we are really passing is the address of array in memory. Then, the arr parameter will be initialized to reference the same array in memory. When we set every element in arr (which is the SAME array as array) to zero, then it does change the original array. So when we print out array in main after the call to zeroArray, it will print out all 0’s for the elements (because every element is set to zero in the zeroArray method).
From Main Method to Multiple Methods Now that we’ve seen how to write separate methods, we need to learn how to reorganize our main method-only programs to use multiple methods. Here are some general rules for organizing your programs:
Suppose we want to write a program that plays a simplified version of Hangman. We will ask the user for a word, and then print out a _ for each letter. We will then repeatedly have the user to guess a letter and then replace each _ with the letter (if it was a correct substitution based on the original word). We will continue this process until the entire word has been guessed.
Here is a main method-only solution to our game:
import java.util.*;
public class Hangman { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter a word: "); String word = s.nextLine();
String result = ""; for (int i = 0; i < word.length(); i++) { result += "_"; }
System.out.println("\nCurrent word: " + result); while (!(result.equals(word))) { System.out.print("\nGuess a letter: "); char letter = (s.nextLine()).charAt(0);
boolean contains = false;
//returns a string of size ‘’ characters public static string init(int size) { String result = ""; for (int i = 0; i < size; i++) { result += ""; }
return result; }
//asks the user for a letter //replaces all _ characters in cur when the corresponding //character in orig matches the input letter //return the updated orig string public static string guessLetter(String orig, String cur) { System.out.print("\nGuess a letter: "); char letter = (s.nextLine()).charAt(0);
for (int i = 0; i < orig.length(); i++) { if (orig.charAt(i) == letter) { cur = cur.substring(0, i) + letter + cur.substring(i+1); } }
return cur; }
//if update is true, print cur //otherwise, print that the most recent letter wasn’t in our word public static void printResults(string cur, bool update) { if (update == true) { Console.WriteLine("\nCurrent word: " + cur); } else { Console.WriteLine("\nThe letter is not in the word"); } } }
Notice that we can still look at our main method to figure out the flow of the program (the order in which things happen). However, the main method is now a lot easier to read because the details have been passed off to other methods.