Download Introduction to Java Methods

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
ICS 3U1
Unit 3 – Methods
Name: _______________
Introduction to Java Methods
In larger software projects, we may find code needs to be repeated often. For instance, the
following code was the basis for many of your early programs:
// Create a Scanner to retrieve input.
Scanner sc = new Scanner (System.in);
// Request input from the user.
System.out.print(“Please enter an integer: “);
int num = sc.nextInt();
In game programming, code such as the lines shown above may be repeated several times. To
clean up our code, it’d be best if we could reuse certain sections.
Modular Programming
Complex problems are easier to solve in pieces. Rather than tackling the problem all-at-once,
consider breaking it into sub-problems. After solving each sub-problem, the smaller solutions
can be combined into a solution to the entire problem.
This is known as modular programming, where the program is broken into separate parts, or
modules, which are then assembled into an overall solution.
Modular programming offers some distinct advantages:
• Breaks the problem into smaller pieces that are easier to understand and solve.
e.g. a video game can be program down into its graphics (visuals) and its engine (logic)
• Multiple programmers can work on the same overall problem by solving its sub-problems.
e.g. programmers working on the graphics can independently work on 3D models, animation
sequences, or thematic movies
• Modules can be reused in other parts of the program.
e.g. a “death animation” can be re-used in various parts of the game
• Some modules can be reused in other programs.
e.g. the Quake game engine has been re-used for many other games
• A module is easier to test in detail than a larger program solving a complicated problem.
e.g. you can test if a gun is firing properly without having created all of the Call of Duty maps
ICS 3U1
Unit 3 – Methods
Name: _______________
Java Methods
A method is a block of reusable code in Java. In fact, you’ve used several already!
- The print() method of the Scanner class is used to produce output.
- The String class has built-in methods such as equals() and charAt() for String manipulation.
- The Math class has the random() method used for obtaining random numbers.
So far, the only method we have written is the main() method. This method is automatically
executed when we run our Java program.
A method is defined outside of the main method using the following syntax:
public static <return type> <method name>()
{
// Code goes here.
// If the method is supposed to calculate and
// return an answer, use the line below.
return <value to be returned>;
}
where:



<return type> is the data type returned by the method -- void if
nothing is to be returned
<method name> is the name of the method e.g. random, getAnswer, etc.
The keyword static is used to allow this method to be used anywhere.
Example: Suppose we are writing a program that requires the identical address information to
be output at regular intervals.
Ahmed's Video Wonderland
123 Roehampton Avenue
613-555-1212
The following code can be used to output this information whenever we need it by calling the
associated method. This is the method definition below:
public static void printHeading()
{
System.out.println("Allan's Video Wonderland");
System.out.println("123 Roehampton Avenue");
System.out.println("613-555-1212");
}
Note: The return type of this method is void since the method does not return anything.
ICS 3U1
Unit 3 – Methods
Name: _______________
To use this method, the simplest option is to call, or invoke, the printHeading() method from
within the main() method. When the main() method executes, it finds the reference to the
printHeading() method, and executes the code within it. The entire program is shown below.
class Sample
{
public static void printHeading ()
{
System.out.println("Ahmed's Video Wonderland");
System.out.println("123 Roehampton Avenue");
System.out.println("613-555-1212");
}
public static void main (String[] args)
{
printHeading();
}
}
Note that we need to include the parentheses and semicolon with the call to printHeading()
in the main() method. This lets Java know that printHeading() is a method, and not simply a
variable.
Example: The getNumber() method below will ask the user for an integer and then return it.
public static int getNumber ()
{
// Create a Scanner to retrieve input.
Scanner sc = new Scanner (System.in);
// Request input from the user.
System.out.print(“Please enter an integer: “);
int num = sc.nextInt();
// Return the int value to the calling method.
return num;
}
Notice that the return type is int and the type of the return value is int.
To use this function, it can also be called from within the main() method.
public static void main (String[] args)
{
getNumber();
}
ICS 3U1
Unit 3 – Methods
Name: _______________
PROBLEM: The above code demonstrates a very common mistake that won’t throw an error.
The code in main() calls the getNumber() method and waits for it to return.
The getNumber() method will ask for an input and return it to the calling method (main).
However, main() does nothing with that return value! We want to create a variable that will
receive that return value. This can be modified as follows.
public static void main (String[] args)
{
// Retrieve an integer from the input and
// save it in the variable userInput.
int userInput = getNumber();
}
ICS 3U1
Unit 3 – Methods
Name: _______________
Assignment – Introduction to Methods
Note: All methods from these exercise should be saved in one file called Methods.java. You
may find it useful to write a main() method for yourself to test your methods, but you do not
have to include one in your submission.
1. Write a method called rollDice() that will simulate the results of rolling a single fair die
by returning a random integer value in the range 1 to 6.
2. Write a method called getCourseAverage() that will ask the user for the number of
courses n that they’ve taken. The method will then ask for the n grades obtained in those
courses and return their average.
3. Write a method called countdown() that prints a countdown from 10 to 0 with a halfsecond delay between each number. The command Thread.sleep(500) will cause the desired
delay.