Transcript Looping
Methods II
Material from Chapters 5 & 6
Note on the Slides
We have started to learn how to write nonprogram Java files
classes with functions/methods, but no main
In order to use them, we need a program…
program tells non-program what to do
…so we need two (or more) files
code for program file will be in yellow
code for non-program file(s) will be in green
Last Time
Methods that return values
method call: returnType var = Class.name(arg);
method definition:
public class Class {
public static returnType name(pType param) {
// body goes here (if needed)
return result;
}
} » need to fill in return type, parameters, body & result
» there may be more parameters, or none
This Time
Methods that do not return a value
“procedures”
AKA: “void methods”, “void functions”
» I don’t like “void functions”, but some people do
Used differently than function methods
void method call: Class.name(arg);
there’s no return value, and so nothing to “use”
» may be no arguments, or several
Two Kinds of Methods
Some methods return a value to you
nextInt returns an int
fahrenheitFromCelsius returns a double
equalsIgnoreCase returns a boolean
These called value-returning methods
Other methods do not return values
print and println, for example
Those are called void methods
Value-Returning Function Calls
word = keyboard.next();
Object
Method Name
Method Arguments
while (!word.equals(“.”))
Value-returning functions used in
expressions
often in assignment statements
also in logical expressions
Void Function Calls
System.out.print(“Enter a #”);
Object
Method Name
Method Arguments
System.out.print(“\n\n”);
Void functions used as complete statements
not in any expression
have no value (“void” = empty/nothing)
Return or No Return?
Void methods do things; don’t return things
println prints a String
the String gets printed
the String does not get returned
String s = System.out.println(“Hello?”);
incompatible types: void cannot be converted to String
nothing gets returned!
int n = System.out.println(“10”);
incompatible types: void cannot be converted to int
Exercise
Void or value-returning?
& what kind of value does each VRM return?
if (answer.startsWith(“Y”)) {
double x = Math.pow(3, 6);
int n = kbd.nextInt();
System.out.println(“Hello!”);
myWin.setVisible(true);
double cm = Converter.cmFromFeetInches(n, x);
thingamajig.doStuff(cm, x, that.get(n));
}
Note: there are two method calls on the last line.
How can we find out what kind of value get returns?
void Method Definition
Very similar to function method definition
put “void” for the return type
» “void” means “nothing”: the method returns nothing
don’t use a return command
» there’s nothing to return!
public class Class {
public static void name(pType param) {
// body goes here
}
}
What’s it for?
It’s to do things
for example, to print something:
System.out.println(“Hello, World!”);
System.out is the object (it’s a PrintWriter)
» System is a class, and out belongs to System
println is the name of the method
println expects to be given a String
» (or some other thing, or nothing; it’s complicated)
Example
Write a method that prints out the selfidentification for A07:
A00000000 -- Young, Mark
CSCI 1226 -- Fall 2014
A07 -- due 2014-10-31
Including the blank lines before and after
Call like this:
Utilities.printA07Identification();
What is the method’s name? What class is it defined in?
How can we tell it’s a void method?
printA07Identification
Start with just a stub
a small definition that compiles
public class Utilities {
public static void printA07Identification() {
}
}
Note: void methods have no return command
» so void method stub can actually be empty
maybe S.o.pln(“Print A07 identification here”);
printA07Identification
Add code to do what needs doing
one command, or many
public static void printA07Identification() {
System.out.println();
System.out.println(“A00000000 -- Young, Mark”);
System.out.println(“CSCI 1226 -- Fall 2014”);
System.out.println(“A07 -- due 2014-10-31”);
System.out.println();
}
Arguments to a Method
Sometimes need to give more information
What is it you want me to print?
What distance do you want me to convert?
In parentheses after the method name
System.out.println(“OK!”);
cm = Converter.cmFromFeetInches(3, 5);
Still need parentheses even if no arguments
num = kbd.nextInt();
Utilities.printA07Identification();
Arguments and Parameters
Method definition needs one parameter for
each argument
parameter is a variable to hold the argument
Parameter must be the right data type
argument is double parameter is double
argument is String parameter is String
argument is boolean parameter is boolean
argument is int parameter is int (or double)
» computer will change int to double when it needs to
Method Parameters
public static double fahrenheitFromCelsius(double degC) {
…
}
double degC
needs to be given a double value (int is OK)
» it will be given a value!
» not giving it a value is a mistake (syntax error)
it will call the value it’s been given degC
» it might be 10.0, 37.5, -40.0, 10000000.0, …
» whatever it is, it’s saved in degC
Method Parameters
public static double cmFromFeetInches(int ft, double in) {
…
}
This method has two parameters
it’s expecting to be given two things
the first thing will be an int (we’ll call it ft)
the second thing will be a double (in)
Arguments & parameters match up in
order – first argument first parameter,
second argument second parameter, …
Parameters are Local
The method’s parameter(s) can only be used
in that method
just like a for loop’s loop control variable
You can give it any (valid) name you want
doesn’t matter who else uses that name
» or if no one else uses that name
should say what it holds, tho
» ft holds # of feet, degC holds a temp. in Celsius.
Local Variables
public static double fahrenheitFromCelsius(double degC) {
double degF = 32.0 + 9.0 * degC / 5.0;
return degF;
}
for (int c = 0; c < 10; ++c) {
Assign return value
Converter.fahrenheitFromCelsius(c); to new variable
Sopln(degC + “C is ” + degF + “F”);
Symbol not found: degC
}
Symbol not found: degF
Hacking
public static double fahrenheitFromCelsius(double degC) {
double degF = 32.0 + 9.0 * degC / 5.0;
return degF;
}
for (int c = 0; c < 10; ++c) {
double degC, degF;
Converter.fahrenheitFromCelsius(c);
Sopln(degC + “C is ” + degF + “F”);
}
Assign return value
to new variable
degC not initialized
degF not initialized
Hacking
public static double fahrenheitFromCelsius(double degC) {
double degF = 32.0 + 9.0 * degC / 5.0;
return degF;
}
for (int c = 0; c < 10; ++c) {
double degC = 0.0, degF = 0.0;
Assign return value
Converter.fahrenheitFromCelsius(c); to new variable
Sopln(degC + “C is ” + degF + “F”); 0.0C is 0.0F
0.0C is 0.0F
}
0.0C is 0.0F
0.0C is 0.0F
0.0C is 0.0F
Hacking
public static double fahrenheitFromCelsius(double degC) {
double degF = 32.0 + 9.0 * degC / 5.0;
return degF;
}
for (int c = 0; c < 10; ++c) {
double degC = 0.0, degF = 0.0;
degF = Converter.fahrenheitFromCelsius(c);
Sopln(degC + “C is ” + degF + “F”); 0.0C is 32.0F
0.0C is 33.8F
}
0.0C is 35.6F
0.0C is 37.4F
0.0C is 39.2F
Local Variables
public static double fahrenheitFromCelsius(double degC) {
double degF = 32.0 + 9.0 * degC / 5.0;
return degF;
}
for (int c = 0; c < 10; ++c) {
double f = Converter.fahrenheitFromCelsius(c);
Sopln(c + “C is ” + f + “F”);
0C is 32.0F
}
1C
2C
3C
4C
is
is
is
is
33.8F
35.6F
37.4F
39.2F
Arguments
Remember that arguments are extra
information we give to a method
information it needs to do its job
Each time you call the method, the
arguments are “passed to” the method, and
it uses them
System.out.println(“Hello!”); prints “Hello!”
System.out.println(“Bye!”); prints “Bye!
Arguments to User Methods
User methods are the same!
Utilities.printAssignmentIdentification(7, “2014-10-31”);
A00000000 -- Young, Mark
CSCI 1226 -- Fall 2014
A07 -- due 2014-10-31
Utilities.printAssignmentIdentification(8, “2014-11-07”);
A00000000 -- Young, Mark
CSCI 1226 -- Fall 2014
A08 -- due 2014-11-07
Exercise
Write that method:
Utilities.printAssignmentIdentification(7, “2014-10-31”);
A00000000 -- Young, Mark
CSCI 1226 -- Fall 2014
A07 -- due 2014-10-31
What’s its name?
What class is it in?
What kinds of arguments does it take?
» what are those arguments for?
System.out.printf(“A%02d”, 1); will print A01
More Utilities Methods
A class with helpful printing methods
use it like this:
Utilities.printTitle(“Utilities Demo”);
Utilities.printParagraph(“This program demonstrates ”
+ “the Utilities class.”);
Utilities.printParagraph(“This paragraph was produced ”
+ “by the printParagraph method.”);
Utilities.printParagraph(“This paragraph’s much longer ”
+ “than the one above, and needs to be \“wrapped\” ”
+ “on the output line. The method does that for us!”);
PrintHelper Methods
printTitle print underlined, with blank lines
printParagraph wrap words, add blank line
Utilities Demo
-------------This program demonstrates the Utilities class.
This paragraph was produced by the printParagraph method.
This paragraph’s much longer than the one above and needs to be
“wrapped” on the output line. The method does that for us!
Utilities Class Stubs
public class Utilities{
public static void printAssignmentIdentification
(int a, String d) {
}
public static void printTitle(String title) {
}
public static void printParagraph(String text) {
}
}
printTitle Body
public void printTitle(String title) {
System.out.print("\n" + title + "\n");
for (int i = 1; i <= title.length(); i++)
System.out.print('-');
System.out.print("\n\n");
}
print blank line and title; end title line
for each letter in the title
» print a hyphen (to underline that letter)
end underline line, print blank line
printParagraph Body
printParagraph is more complicated
needs to break the String into words
needs to print each word, BUT…
… before it prints a word, it needs to know if
there’s enuf space for it
» if not, we need to end the line before we print it
» so needs to keep track of how much space is used
but it’s just a programming problem
» same as if we’d asked for a program to do it
It does use an array, tho’, so I won’t explain how it works in detail.
Naming Methods
Method names in mixed case
capital letter for 2nd and subsequent words
Value-returning methods have noun-like
names
say what the value is: fahrenheitFromCelsius
void functions have command-like names
tell computer what to do: printTitle
Exercise
Create names for the following methods
gives us the factorial value of a number
» (e.g. 5! = 5 * 4 * 3 * 2 * 1 = 120)
figures out how many students failed a test
a) ... and returns that value to us
b) ... and prints a message telling us the number
draws a snowman in a (given) window
Commenting Methods
Methods should have javadoc comments
start with /**, end with */
at least a brief description of the method:
/** Prints the identification information for A07. */
/** Prints title underlined, with blank lines around it. */
hover over method header in Navigator pane…
» lower left side of NetBeans window
…to see your comment
Commenting Methods
Better (but NOT REQUIRED):
add @param for each parameter (if any)
add @return if it’s a value-returning method
/**
* Converts distance from feet and inches to centimetres.
*
* @param ft (whole) number of feet in the distance
* @param in number of (extra) inches in the distance
* @return same distance, but measured in centimetres
*/
Commenting Methods
A longer description may be appropriate.
add HTML markup to format the comment
/**
* Print a paragraph, wrapped to 80 characters per line.
* <p>
* The paragraph has a blank line printed after it.
* If the text contains a word of over 80 characters,
* that word will overflow the right edge of the paragraph.
* (This method does not hyphenate words.)
*
* @param text the text of the paragraph to be printed.
*/
<p> is HTML for “start a new paragraph.”
You DO NOT need to learn HTML for this course!
Questions