Java Reference
In-Depth Information
castIntoBlackHole is a name we just made up; it is the name of the func-
tion, and the () characters indicate that it is a function and will take the
arguments we've listed. You always need the parentheses, even if the
function doesn't take any arguments.
In this case, it takes one argument we named playerName , which it expects
to be a String . For each argument your function accepts, you need to specify
both a variable name and its type. Your function can take multiple arguments;
you use a comma to separate each pair made up of the type and variable (like
we did back in the helloCommand in HelloWorld ).
In between the braces, {} , are where the code for this function goes. You can
put as much code in a function as you want, but a good rule of thumb is to
not make it any longer than maybe 30 lines. Shorter is always better; if you
find yourself writing very long functions, you will want to break those up into
several smaller functions to help make the code easier to read.
Here's an example of a function that returns a value; it will triple any number
you give it:
public static double multiplyByThree( double amt)
{
double result = amt * 3.0;
return result;
}
This function calculates a result and uses the return keyword to return that
value to the caller. You would call the multiplyByThree function and assign the
returned value to variables like this:
double myResult = multiplyByThree(10.0);
double myOtherResult = multiplyByThree(1.25);
Now myResult will be 30.0, and myOtherResult will be 3.75.
Try This Yourself
You're going to write a function named howlong() to calculate how many seconds
you've been alive:
public static long howlong(int years) {
// Write this function...
}
 
 
Search WWH ::




Custom Search