Chapter I - Learning Management Systems

Chapter VII
User-Created Methods
Chapter VII Topics
7.1 Introduction
7.2 Modular Programming and
Creating Simple Methods
7.3 User-Declared Parameter Methods
7.4 Void Methods and Return Methods
7.5 Introduction to Program Design
7.6 Creating Methods with Other Methods
7.7 Summary
Chapter VII
User-Created Methods
251
7.1 Introduction
Chapter IV introduced a few Java organization concepts. In particular, emphasis
was placed on using class methods. You learned that an object is capable of
containing both data, often called attributes, and action modules that can process
data, called methods. The lion's share of the Chapter IV revolved around using
methods of existing classes. Later you also learned the difference between calling
class methods with the class identifier and object methods with the object
identifier. Class methods are normally utility methods that do not access
changing data fields. The Math class is a good example of a class where data
will not change. There are many methods in the Math class, but only two data
fields, PI and E, which do not change. Methods of the Math class are class
methods and must be accessed using the Math class identifier. If you want to
access the value of PI, you need to use Math.PI in your program. If you want to
compute the square root of 100, you need Math.sqrt(100) in your program.
The same thing is true with methods of the Expo class. If you want to draw a
circle, with a radius of 200, in the center of an 1000 by 650 applet window, you
need the statement Expo.drawCircle(g,500,325,200); in your program. The
point that is being made here is that if you want to call a class method, you need
to use the name of the class.
It is a different story when you have the need to use methods with different sets of
data. In this case, a new and separate object needs to be constructed for every
variable. Most classes require variables for many different data storage situations.
In the last chapter you saw the Bank class. That is a good example of a class,
which requires multiple objects, one for each customer of the Bank class.
Here is an example of using the Bank class:
Bank tom = new Bank();
tom.checkingDeposit(1000);
System.out.println(tom.getChecking);
The point that is being made here is that if you want to call an object method, an
object must be created, and you need to use the name of the object in order to call
the method.
In the statement int num; int is the data type and num is the variable. Likewise
in the statement Bank tom; Bank is the data type and tom is the variable. There
is a very important distinction between simple data types (or primitive data types)
like int, double, and char, and complex data types like Bank and
DecimalFormat.
252
Exposure Java 2013, PreAPCS Edition
05-22-13
A simple/primitive data type can store only one single value. This means an int
can only store one integer. A double can only store one real number. A char can
only store one character. On the other hand, a class is a complex data type. An
object is a complex variable that can store multiple pieces of information (class
attributes) as well as several methods (class actions).
As you saw examples of class methods and object methods, you also learned that
methods can have one or more parameters or arguments. Parameters provide
information to methods for processing. Additionally, methods fall into two major
categories, which are return methods and void methods. Return methods return
some requested value, like the tom.getChecking(); statement, which returns the
checking account balance of the object tom. Void methods do not return any
values. That is why they are called void methods… because their return date type
is void. Void methods frequently alter object data, like the statement:
tom.checkingDeposite(1000.0); which adds $1000.00 to the checking account
balance of the tom object.
Now and then we have students ask, “Mr. Schram, are object methods void or
return methods?” What you need to realize is that the whole class method vs.
object method thing has nothing to do with the whole void method vs. return
method thing. Let us spell it out plainly:
1.
2.
3.
4.
A method can be BOTH a void method and a class method.
A method can be BOTH a void method and an object method.
A method can be BOTH a return method and a class method.
A method can be BOTH a return method and an object method.
So there are void class methods, void object methods, return class methods, and
return object methods.
In this chapter you will learn how to create and write your own class methods and
in the next chapter you will learn how to write your own object methods. You
have already seen that there is a difference in using or calling class methods and
object methods. There is also a difference in writing class methods and object
methods.
As your programs start to increase in size, it becomes important to consider some
proper program design concepts. This chapter will introduce program design with
the use of classes. It is not possible to create large, reliable programs without
being very conscious of program design.
Chapter VII
User-Created Methods
253
7.2 Modular Programming and
Creating Simple Methods
Near the end of this chapter you will see an example of a very poorly written
program, which is then slowly improved with many stages of program design.
The title of this chapter is User Created Methods, but the creation of special
modules, called methods, is motivated by program design. In other words, this
chapter will introduce many introductory program design features.
One important program design feature is modular programming. It is possible to
write a program with hundreds and even thousands of lines of program code that
are all shoved into a single main or paint method. Such a program may work
correctly, but making any fixes or changes to the program will be very difficult.
Imagine the following program. Your program draws a very beautiful horse.
This horse requires 2500 program statements. Now suppose that you have a
gorgeous horse, but the tail is wrong. Fixing the tail problem is difficult with
many program statements bunched together. On the other hand, if you had
created many small modules for each part of the horse, making changes is simple.
If any group of related statements is placed in its own module, called a method in
Java, then you have taken an important step in designing your program.
Another terrific benefit is that methods have a name or identifier. Perhaps the tail
requires fifty lines of programming. Place each one of those statements into one
module and call the module drawTail. Any future programming that needs to fix
or improve the tail is now simpler. Look for the method called drawTail and you
can get started without tedious searching through program statements. This
business of combining common statements into their own modules is called
Modular Programming with the philosophy: One task, one module.
Modular Programming
Modular programming is the process of placing statements
that achieve a common purpose into its own module.
An old programming saying says it well
One Task, One Module
254
Exposure Java 2013, PreAPCS Edition
05-22-13
Using modular programming will start with a very simple program that displays a
mailing address. There is nothing complicated about this program and there is
nothing that demonstrates how to create methods. Program Java0701.java, in
Figure 7.1, shows a program that displays a mailing address and will be used to
introduce the process of creating Java subroutines or methods. This program has
only one method, which is the main method that you have used since the first
Java program. You certainly have used classes and methods since Unit-2, but all
those methods already exist in Java. Now you will learn to create your very own
classes and methods.
Figure 7.1
// Java0701.java
// This program displays a simple mailing address.
// It will be used to demonstrate how to divide program sections of
// the main method into multiple user-created methods.
public class Java0701
{
public static void main(String[] args)
{
System.out.println("Kathy Smith");
System.out.println("7003 Orleans Court");
System.out.println("Kensington, Md. 20795");
System.out.println();
}
}
When you look at this program do take a closer look at the main method. It starts
with a heading that includes the method name main. Then there is a set of braces
that contain the program statements of the method. The entire method, heading
and method body together are inside another container called a class. In this case
that is the Java0701 class. Notice that the class also has a heading with a name
and then a set of braces. With that information we can move on and create our
own methods. Please realize that whether a class or method is already provided
by Java or you create the class and method, the process is identical.
Up to this point, every program you have worked with has had exactly one
method. If it was an application, it was the main method. If it was an applet, it
Chapter VII
User-Created Methods
255
was the paint method. Consider the name of the “main” method. If you have a
main or primary method, would that not imply the existence of other secondary
methods? The answer is “yes” as the next several programs will demonstrate.
Figure 7.2 creates the exact same mailing address as the previous program. This
time there are three other methods in the program besides the main method. The
previous address program statements have been placed in three methods, called
fullName, street and cityStateZip. Each of these new methods is user-created.
Please observe that each method has a heading that follows the same format as the
main method.
The heading starts with public static void followed by the method name
fullName, etc. Once again there is a set of braces { } which contain the method
body of program statements. When you execute a program with multiple
methods, where does it start? It starts with the main method. This is why it is
called the main method in the first place. The main method is now used to call
each one of the new methods in sequence. Make sure that you do not add a semicolon at the end of the method heading. Yes, you are told that every program
statement ends with a semi-colon, but a method heading, class heading or loop
heading is not a program statement and thus does not get a semi-colon.
When you look inside the main method you will see the three method calls.
Now, you have called methods before, and you have always used the class-dotmethod format when doing so. For example, how do you call the sqrt method
from the Math class? You use Math.sqrt. How do you call the drawCircle
method from the Expo class? You use Expo.drawCircle. You use the class
identifier (name of the class), followed by a period, followed by the method
identifier (name of the method).
Calling methods that you have created yourself is no different from calling other
methods. In this program, the name of the class is Java0702. The names of the
methods I want to call are fullName, street, and cityStateZip. So to call these
methods, I need to use the same class-dot-method format. The result is
Java0702.fullname(), Java0702.street(), and Java0702.cityStateZip().
Sometimes students will ask why it is necessary to break up such a small program
into different methods. It does not seem to be necessary. After all, the first
program worked just fine with only the main method. Now, I could include
examples of professional software, which absolutely would not work without
methods; however, such code is thousands of lines long and more than a bit
complex. Please realize the process of breaking a program up into different
methods is the same whether each method has 1 program statement or 1000
program statements. Simplistic examples are often used to help the understanding
of a concept – not to show examples of real world programs which would
overwhelming in a first year computer science course.
256
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.2
// Java0702.java
// This program introduces user-created class methods.
// The three program statements of the Java0702.java program
// are now divided into three user-created methods.
// Each method is called with the class-dot-method format.
public class Java0702
{
public static void main(String[] args)
{
Java0702.fullName();
Java0702.street();
Java0702.cityStateZip();
System.out.println();
}
public static void fullName()
{
System.out.println("Kathy Smith");
}
public static void street()
{
System.out.println("7003 Orleans Court");
}
public static void cityStateZip()
{
System.out.println("Kensington, Md. 20795");
}
}
Chapter VII
User-Created Methods
257
User-Created Method Format
A user-defined method requires:
 A heading, which includes the method name
 A set of { } braces to contain the method body statements
 A body of program statements inside the { } braces
public static void example()
{
System.out.println("This is an example of a");
System.out.println("user-defined method");
}
Program Java0703.java, in Figure 7.3, does exactly the same thing as the
previous program. It has the same exact methods. There is one important
difference – how the methods are called. If you look at the main method, we are
calling the methods without first specifying the name of the class. How does this
work? I mean we cannot find the square root of a number with just sqrt. We
need Math.sqrt. We cannot draw a circle with just drawCircle. We need
Expo.drawCircle. It is always necessary to first specify the name of the class,
and then specify the name of the method… or is it?
Think of mailing a letter. If you live in the United States, and you send a letter to
someone else in the United States, do you need to include “U.S.A.” in the
address? No, you do not because you are already in the United States. What if
you did include “U.S.A.” in the address? Would that be a problem? No, it is just
extra information. This is essentially what is happening with this program, and
the previous one.
In program Java0703.java, we can call the fullName, street, and cityStateZip
methods without using the name of the class because all of these methods are in
the same class as the main method. So this is the one exception to the class-dotmethod rule. If both the method you are calling, and the method you are calling
from (usually the main method) are in the same class, you do not need to use the
name of the class. You still can if you really want to -- l ike in program
Java0702.java – but it is not necessary.
258
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.3
// Java0703.java
// This program example displays the same output as the previous program.
// This time the methods are called without using the name of the class.
// Omitting the class identifier is possible because all the methods are
// in the same class, Java0703.
public class Java0703
{
public static void main(String[] args)
{
fullName();
street();
cityStateZip();
System.out.println();
}
public static void fullName()
{
System.out.println("Kathy Smith");
}
public static void street()
{
System.out.println("7003 Orleans Court");
}
public static void cityStateZip()
{
System.out.println("Kensington, Md. 20795");
}
}
The previous two programs placed each of the new methods inside the same class
as the main method. Program Java0704.java, in Figure 7.4, creates a userdefined Address class and places the three new methods inside that class instead.
Chapter VII
User-Created Methods
259
Figure 7.4
// Java0704.java
// This program demonstrates how to use a second class separate
// from the main program class.
// This program will not compile, because the <fullName>, <street>
// and <cityStateZip> methods are no longer contained in the <Java0703> class.
public class Java0704
{
public static void main(String args[])
{
fullName();
street();
cityStateZip();
System.out.println();
}
}
class Address
{
public static void fullName()
{
System.out.println("Kathy Smith");
}
public static void street()
{
System.out.println("7003 Orleans Court");
}
public static void cityStateZip()
{
System.out.println("Kensington, Md. 20795");
}
}
A class is considered a toolkit and methods are considered tools. A well-designed
program creates separate classes to contain a common set of methods designed for
a similar purpose. In the case of Java0704.java all three of the methods are
involved with the display of a mailing address. It makes sense to place these three
methods inside a common class, called Address.
It is all very nice, but Figure 7.5 shows that the Java compiler is not happy and
generates three errors at compile time. Each of the errors indicates that Java
cannot find the three new methods. The previous program had no difficulty, but
then the new methods were in the same container as the main method. A
program statement in one class cannot call a method in another class using only
the method name.
260
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.5
Think again about the “mail” analogy that I used earlier. What if you were on
vacation in Rome and you were mailing a letter to a friend in the United States?
In that case you must include U.S.A. in the address.
It is a good idea and it is considered good program design, to place common
purpose methods inside their own class container. You just need to make sure
that you include the class name with the method name when such methods are
used. Program Java0705.java, in Figure 7.6, has the exact same Address class,
but this time you will see in the main method that each method call starts with the
class name Address. We are again using the proper class-dot-method format.
Figure 7.6
// Java0705.java
// The problem of <Java0704.java> is now fixed.
// It is possible to declare multiple classes in one program,
// but you must use the class-dot-method format to call
// any of the <Address> class methods.
public class Java0705
{
public static void main(String args[])
{
Address.fullName();
Address.street();
Address.cityStateZip();
System.out.println();
}
}
class Address
{
public static void fullName()
{
System.out.println("Kathy Smith");
}
public static void street()
{
Chapter VII
User-Created Methods
261
System.out.println("7003 Orleans Court");
}
public static void cityStateZip()
{
System.out.println("Kensington, Md. 20795");
}
}
Figure 7.6 Continued
Using the Class Identifier
The name of the class is called the class identifier.
Using the class identifier is optional if you are calling a method
that is in the same class.
Using the class identifier is required if you are calling a method
that is in a different class.
The past couple programs have something new that you have not seen before.
They each contain more than one class. Declaring a second class in a Java file is
not a problem. The syntax of a second class is almost identical to the primary
class with one important distinction. A second and third class, placed in the same
file, should not be declared public. Only the primary class, the one with the same
name as the file, is public.
The first set of programs has shown the format of a user-defined method, but
these examples have hardly shown any motivation for such methods. It certainly
is simpler to display a three-line mailing address with three program statements
then it is to create three separate methods.
Program Java0706.java, in Figure 7.7, is a graphics program that draws a house.
It is not a large program, but it has sufficient length that the program statements
do not make it clear that a house is drawn. It is also not clear which program
statements are responsible for the roof, chimney, windows, etc.
262
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.7
// Java0706.java
// This program draws a house by placing all the necessary
// program statements inside the <paint> method.
// This is an example of poor program design.
import java.awt.*;
import java.applet.*;
public class Java0706 extends Applet
{
public void paint(Graphics g)
{
Expo.setColor(g,Expo.blue);
Expo.drawRectangle(g,200,200,500,300);
Expo.drawRectangle(g,200,300,500,400);
Expo.setColor(g,Expo.red);
Expo.drawLine(g,200,200,350,100);
Expo.drawLine(g,500,200,350,100);
Expo.drawLine(g,200,200,500,200);
Expo.setColor(g,Expo.red);
Expo.drawLine(g,420,146,420,80);
Expo.drawLine(g,420,80,450,80);
Expo.drawLine(g,450,80,450,166);
Expo.setColor(g,Expo.black);
Expo.drawRectangle(g,330,340,370,400);
Expo.drawOval(g,350,370,10,20);
Expo.fillCircle(g,366,370,3);
Expo.setColor(g,Expo.black);
Expo.drawRectangle(g,220,220,280,280);
Expo.drawLine(g,220,250,280,250);
Expo.drawLine(g,250,220,250,280);
Expo.drawRectangle(g,420,220,480,280);
Expo.drawLine(g,420,250,480,250);
Expo.drawLine(g,450,220,450,280);
Expo.drawRectangle(g,320,220,380,280);
Expo.drawLine(g,320,250,380,250);
Expo.drawLine(g,350,220,350,280);
Expo.drawRectangle(g,220,320,280,380);
Expo.drawLine(g,220,350,280,350);
Expo.drawLine(g,250,320,250,380);
Expo.drawRectangle(g,420,320,480,380);
Expo.drawLine(g,420,350,480,350);
Expo.drawLine(g,450,320,450,380);
}
}
Chapter VII
User-Created Methods
263
Please realize that program Java0706.java has very poor design. This is because
all of the program statements are in the paint method. For applications, it would
also be considered poor design to put all of the program statements are in the
main method. A well designed program is broken up into different methods –
one for each task.
You may still not appreciate what the point is. Imagine that you do not like the
appearance of the chimney. Where in the paint method do you go to make the
changes? It is not really easy to see. We will improve this in the next section.
Why don’t we improve it in this section? This section is titled Modular
Programming and Creating Simple Methods.
Simple methods are methods
without parameters. Parameters methods have more functionality and will work
very nicely to make our house program much more organized.
I hope you understand that the house displayed in figure 7.7 can easily be made
far more complex with hundreds of program statements. Just imagine if the house
includes actual bricks, bushes, plants in the windows, a number on the doors,
Christmas lights, and kids playing in the yard. In no time a project as the one
described requires more than 1000 program statements. Placing all those
statements in one single paint method is very poor program design. Making any
changes becomes very tedious. Even with this relatively small program could you
tell by the program statements that they will draw a house?
Sometimes when students work on a program that contains too many lines in one
module, they argue that they know the purpose of each program statement. This
is quite true when the program writing is fresh in your mind. It is a different story
when time goes by. We wrote an Academic Decathlon program of about 12,000
lines about twenty years ago. We were in a hurry to meet a deadline. The
program lacked proper modular program design and comments were pretty much
non-existent. In the heat of writing the program day after day, we stayed on top
of everything. Then we received a wake-up call one year later. It was a program
for Academic Decathlon data processing and there were major changes. Altering
the poorly-designed program a year later was a nightmare.
264
Exposure Java 2013, PreAPCS Edition
05-22-13
7.3 User-Declared Parameter Methods
You have seen many program statements that call a wide variety of different
methods. The majority of those methods use parameters or arguments to perform
a desired computation. You do know that some methods do not require
parameters, but most methods require some type of information for processing.
In some cases, methods are overloaded. This means they can be used in different
situations with different types of parameters or a different number of parameters.
Methods Calls With and Without Parameters
Parameter method examples:
double result1 = Math.sqrt(100);
double result2 = Math.pow(2,5);
Expo.delay(3000);
Expo.drawCircle(g,500,325,100);
Non-Parameter method examples:
Bug barry = new Bug( );
barry.move( );
barry.turn( );
Overloaded method examples:
System.out.println(“Hello World”);
System.out.println( );
Expo.setColor(g,Expo.red);
Expo.setColor(g,150,100,15);
Expo.drawPolygon(g,100,100,700,100,400,400);
Expo.drawPolygon(g,500,100,800,200,600,400,400,400,200,200);
Chapter VII
User-Created Methods
265
Why is it that so many methods require parameters? This is very natural because
methods perform some type of task. In most cases the task requires the
processing of some type of information. A parameter passes this information to a
method.
Look at with Java0707.java, in Figure 7.8. You will see user-defined methods
that each uses one identical parameter. This program takes the previous large
number of program statements and divides them up into separate methods. It is
similar to the mail address program, but has more a practical value. The house
program is divided up into drawFloors, drawRoof, drawDoor, drawWindows
and drawChimney methods.
Look closely at the paint method. Doesn’t it look like an outline? This is what a
paint method or a main method is supposed to look like in a well-designed
program.
Figure 7.8
// Java0707.java
// This program divides all the program statements of the <paint> method
// in the previous program into six separate methods.
import java.awt.*;
import java.applet.*;
public class Java0707 extends Applet
{
public void paint(Graphics g)
{
drawFloors(g);
drawRoof(g);
drawDoor(g);
drawWindows(g);
drawChimney(g);
}
public static void drawFloors(Graphics g)
{
Expo.setColor(g,Expo.blue);
Expo.drawRectangle(g,200,200,500,300);
Expo.drawRectangle(g,200,300,500,400);
}
public static void drawRoof(Graphics g)
{
Expo.setColor(g,Expo.red);
Expo.drawLine(g,200,200,350,100);
Expo.drawLine(g,500,200,350,100);
Expo.drawLine(g,200,200,500,200);
}
public static void drawDoor(Graphics g)
{
Expo.setColor(g,Expo.black);
Expo.drawRectangle(g,330,340,370,400);
266
Exposure Java 2013, PreAPCS Edition
05-22-13
Expo.drawOval(g,350,370,10,20);
Expo.fillCircle(g,366,370,3);
}
public static void drawWindows(Graphics g)
{
Expo.setColor(g,Expo.black);
Expo.drawRectangle(g,220,220,280,280);
Expo.drawLine(g,220,250,280,250);
Expo.drawLine(g,250,220,250,280);
Expo.drawRectangle(g,420,220,480,280);
Expo.drawLine(g,420,250,480,250);
Expo.drawLine(g,450,220,450,280);
Expo.drawRectangle(g,320,220,380,280);
Expo.drawLine(g,320,250,380,250);
Expo.drawLine(g,350,220,350,280);
Expo.drawRectangle(g,220,320,280,380);
Expo.drawLine(g,220,350,280,350);
Expo.drawLine(g,250,320,250,380);
Expo.drawRectangle(g,420,320,480,380);
Expo.drawLine(g,420,350,480,350);
Expo.drawLine(g,450,320,450,380);
}
public static void drawChimney(Graphics g)
{
Expo.setColor(g,Expo.red);
Expo.drawLine(g,420,146,420,80);
Expo.drawLine(g,420,80,450,80);
Expo.drawLine(g,450,80,450,166);
}
}
There is a second reason why the house program is shown. Yes, it is more
complex and hopefully it motivates the use of modular programming, but there is
a special applet issue. The paint method controls the graphics display in the same
manner that the main method controls the sequence in an application program.
If the program now has issues with a weird chimney, a missing window or a door
with the wrong color, it will be easy to find the program code that must be altered
with useful self-commenting names for each method.
Graphical output to an applet window requires the use of a Graphics object. For
simplicity, we have always called this Graphics object g. Any method that needs
to display graphical output requires this Graphics object g. This is why you have
seen it being used as the first parameter in all of the graphics methods of the Expo
class. Now, if you choose to break up a large graphics program into multiple
methods, you need to make sure that you pass the Graphics object g as a
parameter to ALL of these methods.
Removing statements from the main method or the paint method and placing
common purpose statements in separate modules is good. It is good in the sense
that modular programming is used. Object Oriented Design is not satisfied to
Chapter VII
User-Created Methods
267
place common statements in a method. We must continue and improve by
placing common methods into their own class, separate from the driving class.
The driving class is the class that contains either the main method or the paint
method. Program Java0708.java, in figure 7.9, takes the five house draw
methods and places them all inside a House class. Take note that calling these
five methods must now be preceded by using the House identifier.
Figure 7.9
// Java0708.java
// This program places the six methods from the previous program
// into their own <House> class.
import java.awt.*;
import java.applet.*;
public class Java0708 extends Applet
{
public void paint(Graphics g)
{
House.drawFloors(g);
House.drawRoof(g);
House.drawDoor(g);
House.drawWindows(g);
House.drawChimney(g);
}
}
class House
{
public static void drawFloors(Graphics g)
{
Expo.setColor(g,Expo.blue);
Expo.drawRectangle(g,200,200,500,300);
Expo.drawRectangle(g,200,300,500,400);
}
public static void drawRoof(Graphics g)
{
Expo.setColor(g,Expo.red);
Expo.drawLine(g,200,200,350,100);
Expo.drawLine(g,500,200,350,100);
Expo.drawLine(g,200,200,500,200);
}
public static void drawDoor(Graphics g)
{
Expo.setColor(g,Expo.black);
Expo.drawRectangle(g,330,340,370,400);
Expo.drawOval(g,350,370,10,20);
Expo.fillCircle(g,366,370,3);
}
public static void drawWindows(Graphics g)
{
Expo.setColor(g,Expo.black);
268
Exposure Java 2013, PreAPCS Edition
05-22-13
Expo.drawRectangle(g,220,220,280,280);
Expo.drawLine(g,220,250,280,250);
Expo.drawLine(g,250,220,250,280);
Expo.drawRectangle(g,420,220,480,280);
Expo.drawLine(g,420,250,480,250);
Expo.drawLine(g,450,220,450,280);
Expo.drawRectangle(g,320,220,380,280);
Expo.drawLine(g,320,250,380,250);
Expo.drawLine(g,350,220,350,280);
Expo.drawRectangle(g,220,320,280,380);
Expo.drawLine(g,220,350,280,350);
Expo.drawLine(g,250,320,250,380);
Expo.drawRectangle(g,420,320,480,380);
Expo.drawLine(g,420,350,480,350);
Expo.drawLine(g,450,320,450,380);
}
public static void drawChimney(Graphics g)
{
Expo.setColor(g,Expo.red);
Expo.drawLine(g,420,146,420,80);
Expo.drawLine(g,420,80,450,80);
Expo.drawLine(g,450,80,450,166);
}
}
Hopefully, the house program, made you realize that the creation of methods
makes program writing better. It is not only a matter of organizing programs in
such a way that they are more readable. Once a class of methods is created, the
new methods can be used not just once, but multiple times. This means that
creating a practical new class of methods not only helps program organization and
readability, but it also increases efficiency.
Some Program Design Notes
Programs should not be written by placing all the program
statements in the main or paint methods.
Program statements that perform a specific purpose
should be placed inside their own modules. This follows
the one-task, one-module principle of earlier program
design principles.
Object Oriented Design continues by placing modules of a
common nature into a separate class.
Chapter VII
User-Created Methods
269
The creating of the House program may have been good for program
organization, but the parameter passing issue in the form of a Graphics object
might have been less than clear. Program Java0709.java, in Figure 7.10, is a
small program with a small parameter method. When the displayParameter
method is called, the parameter value of 100 is passed to the method, which
displays this value. This is probably not very practical, but it does show how to
call a method with a parameter. It also shows the method heading where the
parameter is declared.
The key difference between creating parameter methods and non-parameter
methods is the parameter declaration. All method declarations have an identifier
followed by parentheses. If no information is required for the method, the
parentheses stay empty. If information is required then the method heading lists
one or more parameters inside the parentheses. Make sure that you include the
data type of each parameter.
Figure 7.10
// Java0709.java
// This program introduces user-defined methods with parameters.
// The purpose of using parameters may be hard to tell, but at this
// stage concentrate on the mechanics and the manner in which information
// is passed from one program module to another program module.
public class Java0709
{
public static void main(String args[])
{
System.out.println("\nJAVA0709.JAVA\n");
displayParameter(100);
System.out.println();
}
public static void displayParameter(int number)
{
System.out.println();
System.out.println("The parameter value is " + number);
System.out.println();
}
}
270
Exposure Java 2013, PreAPCS Edition
05-22-13
Before moving on we need to get used to some parameter vocabulary. There are
two kinds of parameters, which work together to pass information to a method.
The calling parameter is officially called the actual parameter and the receiving
parameter in the method heading is officially called the formal parameter. A
copy of the information is passed from the actual parameter to the formal
parameter.
Actual Parameters and Formal Parameters
The 2 places we find parameters are in the method call
and the method heading:
Method Call Example
displayParameter(100);
Method Heading Example
public static void displayParameter (int number)
{
Parameters in the method call are called actual parameters.
Example: 100
Parameters in the method heading are called formal parameters.
Example: number
The Football Analogy
In American football, the
quarterback passes the ball to the
receiver. When working with
parameters the same thing
essentially happens. The actual
parameter is the quarterback.
The formal parameter is the
receiver. The data that is being
passed from the actual parameter
to the formal parameter is the
football.
Chapter VII
User-Created Methods
271
The formal parameters in the method heading indicate the data types that must be
used by the actual parameters. The previous program example used a constant
integer to pass the information. There are many ways to pass information and
program Java0710.java, in figure 7.11, shows that the actual parameter can take
five different formats. It is possible to use a constant only, a variable only, an
expression with constants only, an expression with a variable and a constant and a
method call that returns the appropriate value.
Figure 7.11
// Java0710.java
// This program demonstrates that the calling parameter can be:
// a constant, like 100.
// a variable, like x
// an expression with only constants, like 100 + 5.
// an expression with a variable and a constant like x + 5.
// a call to a method, which returns a value, like Math.sqrt(100).
public class Java0710
{
public static void main(String args[])
{
System.out.println("\nJAVA0711.JAVA\n");
double x = 100;
displayParameter(100);
displayParameter(x);
displayParameter(100 + 5);
displayParameter(x + 5);
displayParameter(Math.sqrt(100));
System.out.println();
}
public static void displayParameter(double number)
{
System.out.println();
System.out.println("The parameter value is " + number);
System.out.println();
}
}
272
Exposure Java 2013, PreAPCS Edition
05-22-13
Actual Parameters Formats
Actual parameters can be
 constants
(1000)
 variables
(x)
 expressions with constants only
(12 + 13)
 expressions with variables & constants
(x + 3)
 return method calls
(Math.sqrt(4))
You know from using a variety of methods that some methods use more than one
parameter. There is not much to worry about with two parameters. If a method
wants two pieces of information, then by all means provide two values. Program
Java0711.java, in figure 7.12, demonstrates a showArea method. Note also that
the showArea method is intentionally called twice. In this particular example, the
order of the actual parameters makes no difference. In either order the output of
the showArea method is identical.
Figure 7.12
// Java0711.java
// This program demonstrates passing two parameters to a method.
// The <showArea> method is called twice. In this case reversing
// the sequence of the parameters is not a problem.
public class Java0711
{
public static void main(String args[])
{
System.out.println("\nJAVA0711.JAVA\n");
int length = 100;
int width = 50;
showArea(length, width);
showArea(width, length);
System.out.println();
}
public static void showArea(int L, int W)
{
System.out.println();
int area = L * W;
System.out.println("The rectangle area is " + area);
System.out.println();
}
}
Chapter VII
User-Created Methods
273
Figure 7.12 Continued
The reason program Java0711.java has no problem with sequence is due to the
fact that the method operation is multiplication. You should know from Algebra
that P x Q equals Q x P. Mathematical operations do not all have the same
properties. How about subtraction? Can you say that P – Q = Q – P?
This very question is answered by program Java0712.java, in Figure 7.13. Once
again there is a user-defined method that displays the result of a mathematical
operation, but this time it computes the difference. Method showDifference
computes a - b and in this case the sequence of the calling parameters is very
significant. The two outputs are now very different.
Figure 7.13
// Java0712.java
// This program demonstrates that parameter sequence matters.
// In this example method <showDifference> will display different
// results when the calling parameters are reversed.
public class Java0712
{
public static void main(String args[])
{
System.out.println("\nJAVA0712.JAVA\n");
int num1 = 100;
int num2 = 50;
showDifference(num1,num2);
showDifference(num2,num1);
System.out.println();
}
public static void showDifference(int a, int b)
{
System.out.println();
int difference = a – b;
System.out.println("The difference is " + difference);
System.out.println();
}
}
274
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.13 Continued
Actual Parameter Sequence Matters
The first actual parameter passes information to the first
formal parameter.
The second actual parameter passes information to the
second formal parameter.
Parameters placed out of sequence may result in compile
errors or logic errors.
Parameters are tricky critters and students make a bunch of mistakes with
parameters when they are first introduced. Program Java0713.java, in figure
7.14, demonstrates two common errors. Both errors will result in compile errors.
In line 1 two actual parameters, num1 and num2, have data types inside the
parentheses of the method call. This will not work. In line 2 there are two formal
parameters, which appear to be declared as int. This also does not compile. Each
formal parameter requires its own data type.
Figure 7.14
// Java0713.java
// This program demonstrates a common mistake made by students.
// Parameters are declared in the method heading, but may not be
// declared in the method call. This program will not compile.
public class Java0713
{
public static void main(String args[])
{
System.out.println("\nJAVA0713.JAVA\n");
showDifference(int num1, int num2);
// line 1
System.out.println();
}
Chapter VII
User-Created Methods
275
public static void showDifference(int a, b)
// line 2
{
System.out.println();
int difference = a - b;
System.out.println("The difference is " + difference);
System.out.println();
}
}
Figure 7.14 Continued
Common Parameter Mistakes
Wrong
Correct
qwerty(int num1, int num2);
int num1 = 100;
int num2 = 200;
qwerty(num1,num2);
public static void qwerty(int a, b);
public static void qwerty(int a, int b)
You have seen several programs using methods with multiple parameters. In each
case the multiple parameters were all the same data type. This is not a
requirement. Program Java0714.java, in figure 7.15, demonstrates a multi-type
method using three different parameter data types. The program worked because
the data type of each actual parameter matches its corresponding formal
276
Exposure Java 2013, PreAPCS Edition
05-22-13
parameter. You will notice a second method call that is commented out. The
same parameters are in the second call, but they are on the wrong order. If the
comment symbols were removed, the program would try to pass an int to a
String, a double to an int, and a String to a double. This simply would not
compile.
Figure 7.15
// Java0714.java
// This program demonstrates that multiple parameters may be
// different data types. Parameter sequence is very important.
public class Java0714
{
public static void main(String args[])
{
System.out.println("\nJAVA0714.JAVA\n");
multiTypeDemo("Hans",30,3.575);
// three different type parameters method call
//
multiTypeDemo(30,3.575,"Hans");
// same parameters, but in the wrong order
System.out.println();
}
public static void multiTypeDemo(String studentName, int studentAge, double studentGPA)
{
System.out.println("\nThis method has 3 parameters with three different types");
System.out.println("Name: " + studentName);
System.out.println("Age:
" + studentAge);
System.out.println("GPA:
" + studentGPA);
}
}
Output with the comment in place…
Output with the comment removed…
Chapter VII
User-Created Methods
277
You can expect to use parameters in all your future programs. We have helped
hundreds of students in Pascal, C++ and Java with their program problems.
Mistakes that arise from incorrect parameter use certainly are at the top of the list
for programs that do not compile or work logically.
This section will finish with a track analogy. Look at the diagrams carefully and
you will find that they illustrate the correct way to use parameters. Parameters
will simplify your life. Your programs will be better designed. Your programs
will be much shorter by using the same method for multiple situations. At the
same time, your programs can give you headaches if parameters are not used
correctly. Remember that actual parameters and formal parameters must match
in 3 different ways: quantity, type and sequence.
The Track Relay Analogy
Let us summarize this parameter business, with a real life analogy that may help
some students. The analogies that follow explain some of the parameter rules in a
totally different manner. Imagine that you are at a track meet and you are
watching a relay race. In this relay race the starters run 100 meters and then pass
a baton to the next runner in their team.
In the first relay race example, the race official checks the track and announces
that the race is not ready. A look at Race-1 shows there are four starters ready in
their lanes, but only three runners at the 100 meter baton passing mark. A runner
from the Netherlands (NL) is missing.
If the four starting runners represent actual parameters and the three runners at
the 100 meter mark represent formal parameters we have a situation where the
quantity of actual parameters and formal parameters do not match.
Race-1
US
GB
FR
NL
278
Exposure Java 2013, PreAPCS Edition
US
GB
FR
05-22-13
Race-2 presents another situation with a different problem. This time the number
of runners is correct. There are four starters and there are also four runners at the
100 meter mark ready to receive a baton. However two runners at the 100 meter
mark are standing in the wrong lane. The track official announces that the race
cannot start unless the runners change lanes and are ready to receive the batons
from their own countrymen.
This represents a situation where the sequence of actual parameters and formal
parameters do not match.
Race-2
US
GB
FR
NL
US
GB
NL
FR
Race3 is not a problem situation. This race demonstrates an analogy to help
explain the naming of parameters. In Race3, runner John starts for the United
States (US) and passes to Greg. George starts for Great Britain (GB) and passes
to Thomas. Gerard starts for France (FR) and passes to Louis. Finally, Hans
starts for the Netherlands and passes to another guy named Hans.
Race-3
US (John)
GB (George)
FR (Gerald)
NL (Hans)
US (Greg)
GB (Thomas)
FR (Louis)
NL (Hans)
The point of this analogy is that the names do not matter. What matters is that
there are the same number of runners at the passing mark as there are in the
starting blocks. It also matters that everybody stays in their lanes and that the
runners receiving batons are on the same team as the starters.
Note: The batons are not passed based on the names of the runners.
They are passed based on the lanes they run in.
Chapter VII
User-Created Methods
279
Important Rules About Using Methods With Parameters #1
The number of parameters in the method call must match the
number of parameters in the method heading.
The corresponding parameters in the method call must be the
same type as the parameters in the heading.
The sequence of the parameters in the method call must
match the sequence of the parameters in the heading.
The parameter identifiers in the method call may be the same
identifier as or a different identifier from the parameters in the
heading.
If you understand the definitions of actual parameters and formal parameters, it
should make sense that the second set of rules below says the exact same thing as
the first set above. The second set is just a little less wordy.
Important Rules About Using Methods With Parameters #2
The number of actual parameters must match the number of
formal parameters.
The corresponding actual parameters must be the same type
as the formal parameters.
The sequence of the actual parameters must match the
sequence of the formal parameters.
The actual parameter identifiers may be the same identifier as
or a different identifier from as the formal parameters.
280
Exposure Java 2013, PreAPCS Edition
05-22-13
7.4 Void Methods and Return Methods
All the user-declared methods in this chapter have been void methods. You have
already been using both return and void methods in the previous chapter. With
the Bank class you made a deposit with a method call, like:
tom.checkingDeposit(1000.0);
The checkingDeposit method performs some action, which in this case adds
money to your checking account. There is no value returned to the method call.
Such a method is called a void method. Void methods are called as "stand-alone"
program statements.
Return methods always return a value. You do not use a return method call in a
stand-alone statement. A return method call must be part of a program statement,
which uses the value that is returned by the method, like:
System.out.println(tom.getChecking());
The name return method and void method will make more sense when you see
the distinction between the two method declarations in an actual class. In the last
chapter, all the class and method declarations were hidden. In this chapter you
can see the code and this will help to motivate the naming conventions of the
different methods.
Let us start with a Calc class. This is somewhat of a simplified version of the
Java Math class. Furthermore, all the methods in this Calc class are void
methods. You can identify void methods by the headings, which use the reserved
word void. Observant students will now realize that the main method, which you
have used since day one, is also a void method.
Our modest Calc class has only four methods for the four basic arithmetic
operations. Each method requires two parameters, which pass the two operands
for each one of the four binary operations. The methods compute the required
result and then display the two parameters and the calculated result.
This amazing display of Calc class wizardry shown by program Java0715.java,
in figure 7.16, is sure to astound the most discriminating Computer Science
student or even AP Computer Science student.
Chapter VII
User-Created Methods
281
Figure 7.16
// Java0715.java
// This program demonstrates how to create a four-function <Calc> class with void methods.
public class Java0715
{
public static void main(String args[])
{
System.out.println("\nJAVA0715.JAVA\n");
int number1 = 1000;
int number2 = 100;
Calc.add(number1,number2);
Calc.sub(number1,number2);
Calc.mul(number1,number2);
Calc.div(number1,number2);
System.out.println();
}
}
class Calc
{
public static void add(int n1, int n2)
{
int result = n1 + n2;
System.out.println(n1 + " + " + n2 + " = " + result);
}
public static void sub(int n1, int n2)
{
int result = n1 - n2;
System.out.println(n1 + " - " + n2 + " = " + result);
}
public static void mul(int n1, int n2)
{
int result = n1 * n2;
System.out.println(n1 + " * " + n2 + " = " + result);
}
public static void div(int n1, int n2)
{
int result = n1 / n2;
System.out.println(n1 + " / " + n2 + " = " + result);
}
}
282
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.16 Continued
Program Java0717.java, in figure 7.17, demonstrates the syntactical difference
between writing void methods and return methods. Two versions of an add
method are used. add1 is a void method and add2 is a return method. The void
method, add1, uses the reserved word void and displays the result of computing
the sum of the two provided parameter values. The return method add2 uses int
in the method heading in place of void, which indicates the data type of the return
value. Additionally, you will note the reserved word return, which is a required
statement at the end of a return method to indicate which value is returned.
Figure 7.17
// Java0717.java
// This program demonstrates the difference between a
// void <add1> method and a return <add2> method.
// There are two differences.
// Void and return methods are declared differently.
// Void and return methods are also called differently.
public class Java0716
{
public static void main(String args[])
{
System.out.println("\nJAVA0716JAVA\n");
int nbr1 = 1000;
int nbr2 = 100;
add1(nbr1,nbr2);
System.out.println(nbr1 + " + " + nbr2 + " = " + add2(nbr1,nbr2));
System.out.println();
}
public static void add1(int n1, int n2)
{
int sum = n1 + n2;
System.out.println(n1 + " + " + n2 + " = " + sum);
}
Chapter VII
User-Created Methods
283
public static int add2(int n1, int n2)
{
int sum = n1 + n2;
return sum;
}
}
Figure 7.17 Continued
This section concludes by returning to the exciting Calc class. This time the
methods are altered from void methods to return methods. For a calculation
class, return methods are more commonly used. Program Java0717.java, in
figure 7.18, shows the altered, and improved, version of the Calc class. Note:
Putting an entire method on one line is appropriate when the method is very short.
Figure 7.18
// Java0717.java
// This program demonstrates how to create a four-function <Calc> class with return methods.
public class Java0717
{
public static void main(String args[])
{
System.out.println("\nJAVA0717\n");
int nbr1 = 1000;
int nbr2 = 100;
System.out.println(nbr1 + " + " + nbr2 + " = " + Calc.add(nbr1,nbr2));
System.out.println(nbr1 + " - " + nbr2 + " = " + Calc.sub(nbr1,nbr2));
System.out.println(nbr1 + " * " + nbr2 + " = " + Calc.mul(nbr1,nbr2));
System.out.println(nbr1 + " / " + nbr2 + " = " + Calc.div(nbr1,nbr2));
System.out.println();
}
}
class Calc
{
public static int add(int n1, int n2)
public static int sub(int n1, int n2)
public static int mul(int n1, int n2)
public static int div(int n1, int n2)
}
284
{
{
{
{
Exposure Java 2013, PreAPCS Edition
return n1 + n2;
return n1 - n2;
return n1 * n2;
return n1 / n2;
05-22-13
}
}
}
}
Figure 7.18 Continued
7.5 Introduction to Program Design
You are about to study seven stages of a case study. Case studies help to explain
computer science concepts by presenting a sequence of programs. Nobody writes
a complete program instantaneously. Furthermore, many programmers make
mistakes along the way of creating a complete and reliable program. A case study
can also be an excellent tool in program development. Stages in the case study
may intentionally be quite wrong, but they reflect a natural development process.
In other words, it is hardly sufficient to teach computer science by simply
showing a few Java keywords with some program examples to use the keywords.
You also need to learn how to develop your own programs.
The case study that follows will demonstrate the development of a payroll
program. It is the intention of the case study to present the first set of information
on program design. Program design is not an easy topic to teach or learn. There
is quite a subjective side to program design. The Java compiler cares little about
program design.
On the other hand if you need to enhance your program six months later, you will
greatly appreciate if you followed some fundamental rules of design. Likewise if
you leave the job and somebody else takes over from a program that you started,
the new programmer will appreciate if your program is developed in a manner
that makes debugging and enhancement manageable.
Program design does have some chicken and egg problems. The computer
science community is concerned that students learn computer science and will
form bad programming habits if design is not taught immediately. At the same
time program design, makes little sense unless you have some fundamental
knowledge of computer science.
Chapter VII
User-Created Methods
285
Not everybody agrees on the best approach to this design dilemma. At this stage
you have now learned a sufficient amount of computer science to start
investigating issues. The program design treatment in this chapter is not
complete; it is a start. As you learn additional computer science concepts, the
design concern will return at regular intervals.
Payroll Case Study, Stage #1
Stage #1 is a very bad example of program design. I have never seen a student or
anybody else program in this manner. The only reason why this stage is
presented is to make a point. Students frequently complain about the need to use
proper indentations or proper comments. Look at program Jav0718.java, in
figure 7.19. This program actually compiles and executes correctly. All the
source code runs together, there are no meaningful identifiers and no comments.
This type of program is impossible to debug or enhance if it were a large program.
Figure 7.19
// Java0718.java
// Payroll Case Study #1
// The first stage of the Payroll program has correct syntax and logic.
// However, there is no concern about any type of proper program design,
// even to the degree that there is no program indentation. This program is totally unreadable.
import java.text.*; public class Java0718 { public static void main (String args[]) { String a;
double b,c,e,f,g,h,i,j,k; int d; DecimalFormat m = new DecimalFormat("$0.00"); System.out.println(
"\nPAYROLL CASE STUDY #1\n"); System.out.print("Enter Name
===>> "); a = Expo.enterString();
System.out.print("Enter Hours Worked ===>> "); b = Expo.enterDouble(); System.out.print(
"Enter Hourly Rate ===>> "); c = Expo.enterDouble(); System.out.print("Enter Dependents ===>> ");
d = Expo.enterInt(); if (b > 40) { e = b - 40; k = 40 * c; j = e * c * 1.5; } else { k = b * c;
j = 0;
}g=k+j;switch (d) {case 0:f=29.5;break;case 1:f=24.9;break;case 2:f=18.7;break;case 3:f=15.5;break;case 4
:f=12.6;break;case 5:f=10.0;break;default:f=7.5;}i=g*f/100;h=g-i;System.out.println("\n\n");System.out.println(
"Name:
" + a);System.out.println("Hourly rate: " + m.format(c)); System.out.println("Hours worked: " +
b);System.out.println("Dependents: " + d);System.out.println("Tax rate: " + f + "%");System.out.println(
"Regular pay: " + m.format(k));System.out.println("Overtime pay: " + m.format(j));System.out.println("Gross pay:
+m.format(g));System.out.println("Deductions: "+m.format(i));System.out.println("Net pay:
"+m.format(h));
System.out.println("\n\n"); } }
286
Exposure Java 2013, PreAPCS Edition
05-22-13
"
Payroll Case Study, Stage #2
Program Java0719.java, in figure 7.20, makes a small improvement. Every
program statement is written on a separate line. Block structure also uses
indentation to indicate which statement will be executed. At the same time
program statements within the same block are indented the same amount. This
stage is a long way from a well-designed program. Variables like a, b, c, d, etc.
may be fine in Algebra, but they make no sense in a computer program. Does a
mean the gross pay or the net pay? Is b the number of hours worked or the
number of dependents? The program output that follows is identical to the first
stage. Future stages will not include program outputs.
Figure 7.20
// Java0719.java
// Payroll Case Study #2
// The second stage does use indentation, but it is still very poor program design.
// All the program logic is contained in the <main> method and there are no program
// comments anywhere, nor are the identifiers self-commenting.
import java.text.*;
public class Java0719
{
public static void main (String args[])
{
String a;
double b,c,e,f,g,h,i,j,k;
int d;
DecimalFormat m = new DecimalFormat("$0.00");
System.out.println("\nPAYROLL CASE STUDY #2\n");
System.out.print("Enter Name
===>> ");
a = Expo.enterString();
System.out.print("Enter Hours Worked ===>> ");
b = Expo.enterDouble();
System.out.print("Enter Hourly Rate
===>> ");
c = Expo.enterDouble();
System.out.print("Enter Dependents
===>> ");
d = Expo.enterInt();
if (b > 40)
{
e = b - 40;
k = 40 * c;
j = e * c * 1.5;
}
else
{
k = b * c;
j = 0;
}
g = k + j;
switch (d)
{
Chapter VII
User-Created Methods
287
case 0 : f = 29.5; break;
case 1 : f = 24.9; break;
case 2 : f = 18.7; break;
case 3 : f = 15.5; break;
case 4 : f = 12.6; break;
case 5 : f = 10.0; break;
default: f = 7.5;
}
i = g * f / 100;
h = g - i;
System.out.println("\n\n");
System.out.println("Name:
System.out.println("Hourly rate:
System.out.println("Hours worked:
System.out.println("Dependents:
System.out.println("Tax rate:
System.out.println("Regular pay:
System.out.println("Overtime pay:
System.out.println("Gross pay:
System.out.println("Deductions:
System.out.println("Net pay:
System.out.println("\n\n");
" + a);
" + m.format(c));
" + b);
" + d);
" + f + "%");
" + m.format(k));
" + m.format(j));
" + m.format(g));
" + m.format(i));
" + m.format(h));
}
}
Figure 7.20 Continued
288
Exposure Java 2013, PreAPCS Edition
05-22-13
Payroll Case Study, Stage #3
Stage #3 makes a large step forward to improving the program. The single-letter,
meaningless identifiers of the previous stages, are now replaced with very
readable self-commenting identifiers. Programs should have useful comments at
strategic locations in the program, but the first step in commenting is to select
good identifiers. With self-commenting identifiers, like Java0720.java, in figure
7.21, you know anywhere in the program what the purpose of a variable should
be. Identifiers like hoursWorked, grossPay and netPay provide an immediate
clarification for the variable.
Figure 7.21
// Java0720.java
// Payroll Case Study #3
// Stage 3 improves program readability by using meaningful identifiers.
import java.text.*;
public class Java0720
{
public static void main (String args[])
{
String employeeName;
double hoursWorked;
double hourlyRate;
int
numDependents;
double overtimeHours;
double regularPay;
double overtimePay;
double taxRate;
double grossPay;
double taxDeductions;
double netPay;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("\nPAYROLL CASE STUDY #3\n");
System.out.print("Enter Name
===>> ");
employeeName = Expo.enterString();
System.out.print("Enter Hours Worked ===>> ");
hoursWorked = Expo.enterDouble();
System.out.print("Enter Hourly Rate
===>> ");
hourlyRate = Expo.enterDouble();
System.out.print("Enter Dependents
===>> ");
numDependents = Expo.enterInt();
if (hoursWorked > 40)
{
overtimeHours = hoursWorked - 40;
regularPay = 40 * hourlyRate;
overtimePay = overtimeHours * hourlyRate * 1.5;
}
else
{
Chapter VII
User-Created Methods
289
regularPay = hoursWorked * hourlyRate;
overtimePay = 0;
}
grossPay = regularPay + overtimePay;
switch (numDependents)
{
case 0 : taxRate = 29.5; break;
case 1 : taxRate = 24.9; break;
case 2 : taxRate = 18.7; break;
case 3 : taxRate = 15.5; break;
case 4 : taxRate = 12.6; break;
case 5 : taxRate = 10.0; break;
default: taxRate = 7.5;
}
taxDeductions = grossPay * taxRate / 100;
netPay = grossPay - taxDeductions;
System.out.println("\n\n");
System.out.println("Name:
System.out.println("Hourly rate:
System.out.println("Hours worked:
System.out.println("Dependents:
System.out.println("Tax rate:
System.out.println("Regular pay:
System.out.println("Overtime pay:
System.out.println("Gross pay:
System.out.println("Deductions:
System.out.println("Net pay:
System.out.println("\n\n");
" + employeeName);
" + money.format(hourlyRate));
" + hoursWorked);
" + numDependents);
" + taxRate + "%");
" + money.format(regularPay));
" + money.format(overtimePay));
" + money.format(grossPay));
" + money.format(taxDeductions));
" + money.format(netPay));
}
}
Payroll Case Study, Stage #4
Program Java0721.java, in figure 7.22, provides two improvements. Stage #4
adds comments and also separates the program into segments to help identify the
purpose of a program segment. About ten years ago there was a student who
made a beautiful horse for her graphics project. Everything looked great on the
horse except for the tail. The tail was totally wrong and not attached anywhere on
the horse. She asked for help and much to my surprise this student could not tell
me the segment of her program responsible for drawing the tail. She had added
program statement after program statement in one continuous, giant block of
code. Debugging or enhancing such a program becomes a nightmare.
Figure 7.22
// Java0721.java
// Payroll Case Study #4
// Stage 4 separates the program statements in the main method with spaces and comments
// to help identify the purpose for each segment. This helps program debugging and updating.
// Note that this program does not prevents erroneous input.
290
Exposure Java 2013, PreAPCS Edition
05-22-13
import java.text.*;
// used for text output with <DecimalFormat> class.
public class Java0721
{
public static void main (String args[])
{
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Program variables
//
String employeeName; // employee name used on payroll check
double hoursWorked;
// hours worked per week
double hourlyRate;
// employee wage paid per hour
int numDependents;
// number of dependats declared for tax rate purposes
double overtimeHours; // number of hours worked over 40
double regularPay;
// pay earned for up to 40 hours worked
double overtimePay;
// pay earned for hours worked above 40 per week
double taxRate;
// tax rate, based on declared dependents, used for deduction computation
double grossPay;
// total pay earned before deductions
double taxDeductions; // total tax deductions
double netPay;
// total take-home pay, which is printed on the check
//////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
// Program object
//
DecimalFormat money = new DecimalFormat("$0.00");
// money is used to display values in monetary format
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
// Program input
//
System.out.println("\nPAYROLL CASE STUDY #3\n");
System.out.print("Enter Name
===>> ");
employeeName = Expo.enterString();
System.out.print("Enter Hours Worked ===>> ");
hoursWorked = Expo.enterDouble();
System.out.print("Enter Hourly Rate
===>> ");
hourlyRate = Expo.enterDouble();
System.out.print("Enter Dependents
===>> ");
numDependents = Expo.enterInt();
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
// Program computation
//
if (hoursWorked > 40) // qualifies for overtime pay
{
overtimeHours = hoursWorked - 40;
regularPay = 40 * hourlyRate;
overtimePay = overtimeHours * hourlyRate * 1.5;
}
else
// does not qualify for overtime pay
{
regularPay = hoursWorked * hourlyRate;
overtimePay = 0;
}
grossPay = regularPay + overtimePay;
// compute total pay earned before any deductions
Chapter VII
User-Created Methods
291
switch (numDependents)
{
case 0 : taxRate = 29.5; break;
case 1 : taxRate = 24.9; break;
case 2 : taxRate = 18.7; break;
case 3 : taxRate = 15.5; break;
case 4 : taxRate = 12.6; break;
case 5 : taxRate = 10.0; break;
default: taxRate = 7.5;
}
taxDeductions = grossPay * taxRate / 100;
// compute proper tax deductions based on the number of declared dependents
netPay = grossPay - taxDeductions;
// compute actual take-home-pay, which is printed on the paycheck
/////////////////////////////////////////////////////////////////////////////////////////////
// Output display, which simulates the printing of a payroll check
//
System.out.println("\n\n");
System.out.println("Name:
" + employeeName);
System.out.println("Hourly rate:
" + money.format(hourlyRate));
System.out.println("Hours worked: " + hoursWorked);
System.out.println("Dependents:
" + numDependents);
System.out.println("Tax rate:
" + taxRate + "%");
System.out.println("Regular pay:
" + money.format(regularPay));
System.out.println("Overtime pay: " + money.format(overtimePay));
System.out.println("Gross pay:
" + money.format(grossPay));
System.out.println("Deductions:
" + money.format(taxDeductions));
System.out.println("Net pay:
" + money.format(netPay));
System.out.println("\n\n");
/////////////////////////////////////////////////////////////////////////////////////////////
}
}
Payroll Case Study, Stage #5
The first four stages steadily improved from horrible, unreadable chaos, to a
program that is readable and organized. Yet none of them satisfy the fundamental
design principles of Object Oriented Programming. The main method of a
program is not meant to contain detailed code. Program Java0722.java, in figure
7.23, shows the 5th stage. You will observe that the program is divided up into
five segments, each of which becomes a method. While the design and
organization of the program is much improved there is one major issue. The
program does not compile. The issue is not that we broke the program into
different methods… at least not directly. The program has 49 compile errors
because the variables are not dealt with properly. Right now we have all of the
variables defined in the main method, which is what we have always done. Now
that we have multiple methods we need to understand the difference between
local variables and class variables. Local variables are defined inside a particular
method. Only that method will have access to these variables. They simply do
not exist outside of the method. Since all of our variables are defined inside the
main method, they are local to the main method and do not exist anywhere else.
292
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.23
// Java0722.java
// Payroll Case Study #5
// Stage #5 is more in the spirit of modular programming.
// The program is now divided into five separate methods, which
// are called in sequence by the main method.
// There is one major problem which causes many errors.
// All of the variables are defined locally in the <main> method.
// The other methods do not have access to them.
import java.text.*;
public class Java0722
{
public static void main (String args[])
{
String employeeName;
double hoursWorked;
double hourlyRate;
int
numDependents;
double overtimeHours;
double regularPay;
double overtimePay;
double taxRate;
double grossPay;
double taxDeductions;
double netPay;
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("\nPAYROLL CASE STUDY #5\n");
enterData();
computeGrosspay();
computeDeductions();
computeNetpay();
printCheck();
}
public static void enterData()
{
System.out.print("Enter Name
===>> ");
employeeName = Expo.enterString();
System.out.print("Enter Hours Worked ===>> ");
hoursWorked = Expo.enterDouble();
System.out.print("Enter Hourly Rate ===>> ");
hourlyRate = Expo.enterDouble();
System.out.print("Enter Dependents ===>> ");
numDependents = Expo.enterInt();
}
Chapter VII
User-Created Methods
293
public static void computeGrosspay()
{
if (hoursWorked > 40)
{
overtimeHours = hoursWorked - 40;
regularPay = 40 * hourlyRate;
overtimePay = overtimeHours * hourlyRate * 1.5;
}
else
{
regularPay = hoursWorked * hourlyRate;
overtimePay = 0;
}
grossPay = regularPay + overtimePay;
}
public static void computeDeductions()
{
switch (numDependents)
{
case 0 : taxRate = 29.5; break;
case 1 : taxRate = 24.9; break;
case 2 : taxRate = 18.7; break;
case 3 : taxRate = 15.5; break;
case 4 : taxRate = 12.6; break;
case 5 : taxRate = 10.0; break;
default: taxRate = 7.5;
}
taxDeductions = grossPay * taxRate / 100;
}
public static void computeNetpay()
{
netPay = grossPay - taxDeductions;
}
public static void printCheck()
{
System.out.println("\n\n");
System.out.println("Name:
System.out.println("Hourly rate:
System.out.println("Hours worked:
System.out.println("Dependents:
System.out.println("Tax rate:
System.out.println("Regular pay:
System.out.println("Overtime pay:
System.out.println("Gross pay:
System.out.println("Deductions:
System.out.println("Net pay:
System.out.println("\n\n");
" + employeeName);
" + money.format(hourlyRate));
" + hoursWorked);
" + numDependents);
" + taxRate + "%");
" + money.format(regularPay));
" + money.format(overtimePay));
" + money.format(grossPay));
" + money.format(taxDeductions));
" + money.format(netPay));
}
}
294
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.23
Payroll Case Study, Stage #6
To fix the problem from Stage 5, the variables have to be removed from the main
method. Where do we put them? If we put them in any method, they will be
local to that method and no other method will have access. The answer is not to
put them in any method. Local variables are not appropriate in this situation.
What we need are class variables. Class variables are not defined in any method,
but they are defined within the class – usually at the top of the class before the
first method. Class variables can be accessed by ALL methods of that class.
Program Java0723.java, in figure 7.24, used class variables and now it compiles.
Chapter VII
User-Created Methods
295
Figure 7.24
// Java0723.java
// Payroll Case Study #6
// Stage #6 fixes the problem from Stage 5 by using class variables.
// NOTE: The <money> object is defined locally in <printCheck> because
//
that is the only method it is used in.
import java.text.*;
public class Java0723
{
static String
static double
static double
static int
static double
static double
static double
static double
static double
static double
static double
employeeName;
hoursWorked;
hourlyRate;
numDependents;
overtimeHours;
regularPay;
overtimePay;
taxRate;
grossPay;
taxDeductions;
netPay;
public static void main (String args[])
{
System.out.println("\nPAYROLL CASE STUDY #5\n");
enterData();
computeGrosspay();
computeDeductions();
computeNetpay();
printCheck();
}
public static void enterData()
{
System.out.print("Enter Name
employeeName = Expo.enterString();
System.out.print("Enter Hours Worked
hoursWorked = Expo.enterDouble();
System.out.print("Enter Hourly Rate
hourlyRate = Expo.enterDouble();
System.out.print("Enter Dependents
numDependents = Expo.enterInt();
}
===>> ");
===>> ");
===>> ");
===>> ");
public static void computeGrosspay()
{
if (hoursWorked > 40)
{
overtimeHours = hoursWorked - 40;
regularPay = 40 * hourlyRate;
overtimePay = overtimeHours * hourlyRate * 1.5;
}
else
{
regularPay = hoursWorked * hourlyRate;
overtimePay = 0;
296
Exposure Java 2013, PreAPCS Edition
05-22-13
}
grossPay = regularPay + overtimePay;
}
public static void computeDeductions()
{
switch (numDependents)
{
case 0 : taxRate = 29.5; break;
case 1 : taxRate = 24.9; break;
case 2 : taxRate = 18.7; break;
case 3 : taxRate = 15.5; break;
case 4 : taxRate = 12.6; break;
case 5 : taxRate = 10.0; break;
default: taxRate = 7.5;
}
taxDeductions = grossPay * taxRate / 100;
}
public static void computeNetpay()
{
netPay = grossPay - taxDeductions;
}
public static void printCheck()
{
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("\n\n");
System.out.println("Name:
System.out.println("Hourly rate:
System.out.println("Hours worked:
System.out.println("Dependents:
System.out.println("Tax rate:
System.out.println("Regular pay:
System.out.println("Overtime pay:
System.out.println("Gross pay:
System.out.println("Deductions:
System.out.println("Net pay:
System.out.println("\n\n");
" + employeeName);
" + money.format(hourlyRate));
" + hoursWorked);
" + numDependents);
" + taxRate + "%");
" + money.format(regularPay));
" + money.format(overtimePay));
" + money.format(grossPay));
" + money.format(taxDeductions));
" + money.format(netPay));
}
}
If you look closely, you will notice that not every variable in this class is a class
variable. The money object is defined as a local variable in printCheck. This is
also part of proper program design. The money object is only used by method
printCheck, therefore it is defined locally inside printCheck. The other
variables are all used in multiple methods, therefore they are defined as class
variables.
Chapter VII
User-Created Methods
297
Payroll Case Study, Stage #7
In the final stage of this case study you will see a small, but important change.
The driving class of a program, the one that contains the main method or the
paint method, should not be stuffed full of methods.
You have seen earlier that it is desirable to create a toolkit, called a class, filled
with common tools, called methods. With that idea in mind the final stage
presents a Payroll class, which contains all the methods involved with the payroll
processing. Program Java0724.java, in figure 7.25, shows that the Java0724
class now only contains the main which runs or drives the program by making
several calls to methods of the Payroll class.
NOTE: Another word for a Class Variable is an attribute. netPay is an attribute
of the Payroll class just like PI is an attribute of the Math class.
Figure 7.25
// Java0724.java
// Payroll Case Study #7
// In Stage #7 the <main> method is part of the "driving" class, which is the class
// responsible for the program execution sequence. The <main> method now contains
// method calls to objects of the <Payroll> class.
import java.text.*;
public class Java0724
{
public static void main (String args[])
{
System.out.println("\nPAYROLL CASE STUDY #6\n");
Payroll.enterData();
Payroll.computeGrosspay();
Payroll.computeDeductions();
Payroll.computeNetpay();
Payroll.printCheck();
}
}
class Payroll
{
static String
static double
static double
static int
static double
static double
static double
static double
static double
static double
static double
298
employeeName;
hoursWorked;
hourlyRate;
numDependents;
overtimeHours;
regularPay;
overtimePay;
taxRate;
grossPay;
taxDeductions;
netPay;
Exposure Java 2013, PreAPCS Edition
05-22-13
public static void enterData()
{
System.out.print("Enter Name
employeeName = Expo.enterString();
System.out.print("Enter Hours Worked
hoursWorked = Expo.enterDouble();
System.out.print("Enter Hourly Rate
hourlyRate = Expo.enterDouble();
System.out.print("Enter Dependents
numDependents = Expo.enterInt();
}
===>> ");
===>> ");
===>> ");
===>> ");
public static void computeGrosspay()
{
if (hoursWorked > 40)
{
overtimeHours = hoursWorked - 40;
regularPay = 40 * hourlyRate;
overtimePay = overtimeHours * hourlyRate * 1.5;
}
else
{
regularPay = hoursWorked * hourlyRate;
overtimePay = 0;
}
grossPay = regularPay + overtimePay;
}
public static void computeDeductions()
{
switch (numDependents)
{
case 0 : taxRate = 29.5; break;
case 1 : taxRate = 24.9; break;
case 2 : taxRate = 18.7; break;
case 3 : taxRate = 15.5; break;
case 4 : taxRate = 12.6; break;
case 5 : taxRate = 10.0; break;
default: taxRate = 7.5;
}
taxDeductions = grossPay * taxRate / 100;
}
public static void computeNetpay()
{ netPay = grossPay - taxDeductions; }
public static void printCheck()
{
DecimalFormat money = new DecimalFormat("$0.00");
System.out.println("\n\n");
System.out.println("Name:
" + employeeName);
System.out.println("Hourly rate:
" + money.format(hourlyRate));
System.out.println("Hours worked: " + hoursWorked);
System.out.println("Dependents:
" + numDependents);
System.out.println("Tax rate:
" + taxRate + "%");
System.out.println("Regular pay:
" + money.format(regularPay));
System.out.println("Overtime pay: " + money.format(overtimePay));
System.out.println("Gross pay:
" + money.format(grossPay));
System.out.println("Deductions:
" + money.format(taxDeductions));
System.out.println("Net pay:
" + money.format(netPay));
System.out.println("\n\n");
}
}
Chapter VII
User-Created Methods
299
Local Variables and Class Variables
Variables that are declared inside a method or block are called
local variables. Local variables are only accessible inside the
method or block that they are defined in.
Variables that are declared inside a class, but outside any
method, are class variables. Class variables are accessible by
any method of the class.
Class variables are also called attributes.
If a variable is only used by one method, it should be declared
inside that method as a local variable.
If a variable is used by 2 or more methods of a class, it should
be declared as a class variable.
Program Design Notes
This was the first introduction to program design. Additional
design features will be introduced as you learn more ObjectOriented Programming. At this stage you can already consider
the following:
• Programs should use self-commenting identifiers.
• Control structures and block structures need to use a
consistent indentation style.
• Specific tasks should be placed in modules called methods.
• Similar methods accessing the same data should be placed
in a class.
• The main method should be used for program sequence,
not large numbers of program statements.
300
Exposure Java 2013, PreAPCS Edition
05-22-13
After this introduction to program design you should realize that many program
examples that follow in later chapters will actually not follow the very principles
explained in this section. The aim of Exposure Java is to present new concepts
with the smallest, clearest programs so that you learn using one small bite after
another. Many program examples will in fact place the program statements in the
main method. These programs are small and serve their purpose nicely. Creating
separate classes for different purposes with all program examples requires a lot of
space and may obscure the new topics that are introduced.
7.6 Creating Methods with Other Methods
The last method section in this chapter will look at creating some user-defined
methods and then using the newly created methods for more complex methods.
The first program starts with a modest little method that displays a single brown
picket. The picket method in Java0725.java, shown in Figure 7.26, has only two
program statements. It is small, but the program will steadily grow to an
interesting graphics display with many user-defined methods.
Figure 7.26
// Java0725.java
// This program demonstrates a <picket> method that will be used
// to display a fence.
import java.awt.*;
import java.applet.*;
public class Java0725 extends Applet
{
public void paint(Graphics g)
{
Expo.setBackground(g,Expo.black);
Expo.setColor(g,Expo.tan);
Expo.fillRectangle(g,0,500,1000,525);
Expo.fillRectangle(g,0,600,1000,625);
Expo.setColor(g,Expo.brown);
for (int x = 2; x < 1000; x+=40)
{
picket(g,x);
}
}
Chapter VII
User-Created Methods
301
public static void picket(Graphics g, int x)
{
Expo.fillPolygon(g,x,650,x,500,x+18,450,x+36,500,x+36,650);
Expo.delay(250); // delay for ¼ a second
}
}
Figure 7.26 Continued
NOTE: The pickets will show up one at a time. To properly appreciate the
animated output of these graphics programs you need to execute them yourself.
The next program example, Java0726.java, in Figure 7.27, displays the same
picket fence. This time you will see an example of a user-defined method calling
another user-defined method. You will see a new fence method, which uses the
previously created picket method. This follows the philosophy of not reinventing
the wheel.
302
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.27
// Java0726.java
// This program uses the <picket> method to create the <fence> method.
import java.awt.*;
import java.applet.*;
public class Java0726 extends Applet
{
public void paint(Graphics g)
{
Expo.setBackground(g,Expo.black);
fence(g);
}
public static void picket(Graphics g, int x)
{
Expo.fillPolygon(g,x,650,x,500,x+18,450,x+36,500,x+36,650);
Expo.delay(250); // delay for ¼ a second
}
public static void fence(Graphics g)
{
// cross beams
Expo.setColor(g,Expo.tan);
Expo.fillRectangle(g,0,500,1000,525);
Expo.fillRectangle(g,0,600,1000,625);
// pickets
Expo.setColor(g,Expo.brown);
for (int x = 2; x < 1000; x+=40)
{
picket(g,x);
}
}
}
Chapter VII
User-Created Methods
303
Figure 7.27 Continued
The black background is intentional. You will see that Java0727.java, in Figure
7.28, displays a nightSky method, which in turn uses the randomStar and moon
methods. There is also the fence method, which uses the picket method.
There is no end to this process. Java and other program languages allow a
contiuous use of user-defined subroutines to organzie and simplify program
writing. There also is a sense of reliability, because a class can be created by
itself and placed in a program with a tester or runner class to make sure that the
user-defined class and user-defined methods work correctly. A team of
programmers can work together and each take responbility for creating tools that
then turn around and become practical program library of subroutines that can
create very complex programs.
Video games are classic examples of specialized routines that are created to
control game objects in many different situations. If you consider that modern
sophisticated video games are frequerntly more than 500,000 lines of program
code, you can then realize the need for program organization and efficiency.
304
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 7.28
// Java0727.java
// This program combines many user-defined methods to create a graphics image.
import java.awt.*;
import java.applet.*;
public class Java0621 extends Applet
{
public void paint(Graphics g)
{
Expo.setBackground(g,Expo.black);
nightSky(g);
fence(g);
}
public static void randomStar(Graphics g, int x)
{
int y = Expo.random(25,175);
int radius = Expo.random(15,20);
int points = Expo.random(5,10);
Expo.setRandomColor(g);
Expo.fillStar(g,x,y,radius,points);
Expo.delay(250); // delay for ¼ a second
}
public static void nightSky(Graphics g)
{
moon(g);
for (int x = 25; x <= 825; x+= 50)
{
randomStar(g,x);
}
}
public static void moon(Graphics g)
{
Expo.setColor(g,Expo.white);
Expo.fillCircle(g,920,85,70);
Expo.setColor(g,Expo.black);
Expo.fillCircle(g,895,70,60);
}
public static void picket(Graphics g, int x)
{
Expo.fillPolygon(g,x,650,x,500,x+18,450,x+36,500,x+36,650);
Expo.delay(250); // delay for ¼ a second
}
public static void fence(Graphics g)
{
// cross beams
Expo.setColor(g,Expo.tan);
Expo.fillRectangle(g,0,500,1000,525);
Expo.fillRectangle(g,0,600,1000,625);
// pickets
Expo.setColor(g,Expo.brown);
for (int x = 2; x < 1000; x+=40)
{
picket(g,x);
}
}
}
Chapter VII
User-Created Methods
305
Figure 7.28 Continued
The last program in this chapter will display the same night sky graphics program.
This time the entire graphics code is placed inside the paint method. The
program code that is part of a method will be indicated with comments and the
method name. The intention is to show how much more organized and readable a
program is that uses appropriate methods and classes.
Figure 7.29
// Java0728.java
// This program does the exact same thing as the previous program, but without the structure methods.
// Several method calls are commented out and in their place is the code from that method.
// This is also done for some of the methods from the Expo class.
// The intent is to show that using methods makes your program much more readable and easier to work with.
import java.awt.*;
import java.applet.*;
public class Java0728 extends Applet
{
public void paint(Graphics g)
{
///////////////////////////////////////////////////////////////
// Expo.setBackground(g,Expo.black);
Expo.setColor(g,Expo.black);
Expo.fillRectangle(g,0,0,4800,3600);
306
Exposure Java 2013, PreAPCS Edition
05-22-13
//////////////////////////////////////////////////////////////
// nightSky(g);
//////////////////////////////////////////////////////////
// moon(g);
Expo.setColor(g,Expo.white);
Expo.fillCircle(g,920,85,70);
Expo.setColor(g,Expo.black);
Expo.fillCircle(g,895,70,60);
for (int centerX = 25; centerX <= 825; centerX += 50)
{
int centerY = Expo.random(25,175);
int radius = Expo.random(15,20);
int points = Expo.random(5,10);
//////////////////////////////////////////////////////
// Expo.setRandomColor(g);
int red = Expo.random(0,255);
int green = Expo.random(0,255);
int blue = Expo.random(0,255);
Expo.setColor(g,red,green,blue);
/////////////////////////////////////////////////////
// Expo.fillStar(g,x,y,radius,points);
int halfRadius = radius / 2;
switch(points)
{
case 3 : halfRadius = 140 * radius / 500; break;
case 4 : halfRadius = 170 * radius / 400; break;
case 5 : halfRadius = 192 * radius / 500; break;
case 6 : halfRadius = 233 * radius / 400; break;
case 7 : halfRadius = 179 * radius / 500; break;
case 8 : halfRadius = 215 * radius / 400; break;
case 9 : halfRadius = 173 * radius / 500; break;
case 10 : halfRadius = 212 * radius / 400; break;
default : if (points < 52)
{
if (points % 2 == 1)
halfRadius = (180-points) * radius / 500;
else
halfRadius = (222-points) * radius / 400;
}
else
halfRadius = radius / 2;
}
int p = points;
points *= 2;
int xCoord[] = new int[points];
int yCoord[] = new int[points];
int currentRadius;
for (int k = 0; k < points; k++)
{
if (k % 2 == 0)
currentRadius = radius;
else
Chapter VII
User-Created Methods
307
currentRadius = halfRadius;
xCoord[k] = (int) Math.round(Math.cos(2 * Math.PI * k/points - Math.PI/2) * currentRadius) + centerX;
yCoord[k] = (int) Math.round(Math.sin(2 * Math.PI * k/points - Math.PI/2) * currentRadius) + centerY;
}
int x = (p-5)/2+1;
if (p >= 5 && p <= 51)
switch(p % 4)
{
case 1 : yCoord[x] = yCoord[x+1] = yCoord[points-x-1] = yCoord[points-x]; break;
case 2 : yCoord[x] = yCoord[x+1] = yCoord[points-x-1] = yCoord[points-x];
yCoord[x+3] = yCoord[x+4] = yCoord[points-x-4] = yCoord[points-x-3]; break;
case 3 : yCoord[x+2] = yCoord[x+3] = yCoord[points-x-3] = yCoord[points-x-2];
}
g.fillPolygon(xCoord,yCoord,points);
///////////////////////////////////////////////////////
// Expo.delay(250); // delay for ¼ a second
long startDelay = System.currentTimeMillis();
long endDelay = 0;
while (endDelay - startDelay < 250)
endDelay = System.currentTimeMillis();
}
///////////////////////////////////////////////////////////////
// fence(g);
// cross beams
Expo.setColor(g,Expo.tan);
Expo.fillRectangle(g,0,500,1000,525);
Expo.fillRectangle(g,0,600,1000,625);
// pickets
Expo.setColor(g,Expo.brown);
for (int x = 2; x < 1000; x+=40)
{
//////////////////////////////////////////////////////
// picket(g,x);
//////////////////////////////////////////////////
//Expo.fillPolygon(g,x,650,x,500,x+18,450,x+36,500,x+36,650);
Polygon poly = new Polygon();
poly.addPoint(x,650);
poly.addPoint(x,500);
poly.addPoint(x+18,450);
poly.addPoint(x+36,500);
poly.addPoint(x+36,650);
g.fillPolygon(poly);
//////////////////////////////////////////////////
// Expo.delay(250); // delay for ¼ a second
long startDelay = System.currentTimeMillis();
long endDelay = 0;
while (endDelay - startDelay < 250)
endDelay = System.currentTimeMillis();
}
}
}
308
Exposure Java 2013, PreAPCS Edition
05-22-13
Figure 6.23 Continued
7.7 Summary
This chapter focused on writing class methods. Methods can be members in
classes and they can also be members inside an object. The distinction between
creating class methods and object methods will be cleared up when creating
object methods is demonstrated in the next chapter.
Class methods are called by using the class identifier followed by a period and the
method identifier. This is called class-dot-method notation. This type of syntax
is necessary because the class contains multiple members. It requires two
identifiers to first identify the class and then identify the method within the class.
A popular, Java-provided class is the Math class. This class provides a variety of
useful math functions, such as square root, absolute value, truncate, logarithmic
and trigonometric functions.
Chapter VII
User-Created Methods
309
Java allows programmers to declare their own classes and methods. It is possible
to add methods to the existing main class of the program. It is also possible to
declare a second class or multiple classes outside the main class. The Expo class
is an example of a user-defined class that provided many useful tools.
If a statement calls a member method of the same class, the class identifier is
optional. Anytime that a method is called from a class declared outside the
calling statement’s class, the class identifier must be provided.
Methods can be declared with or without parameters. In either case a set of
parentheses follows the method identifier. In the method declaration parameters
need to be declared in the same manner as any other variable declaration, except
that each parameter must have its own data type.
The parameters in the method call must match the parameters in the method
declaration in quantity, type and sequence. Parameters in a method call can be
literal constants, variables or expressions.
This chapter introduced the important concept of program design. Program
design was demonstrated by using a case study that started with a very poorly
written program and improved with small incremental stages.
Finally it was shown that once a method is created, it can be used to create other
methods as well.
310
Exposure Java 2013, PreAPCS Edition
05-22-13