Download presentation
Presentation is loading. Please wait.
1
Exposure Java 2014 For AP®CS Edition
Chapter 7 Slides Creating Class Methods PowerPoint Presentation created by: Mr. John L. M. Schram and Mr. Leon Schram Authors of Exposure Java
2
Section 7.1 Introduction
3
Primitive Data Types vs. Classes
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).
4
“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. A method can be BOTH a void method and a class method. 2. A method can be BOTH a void method and an object method. 3. A method can be BOTH a return method and a class method. 4. 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.
5
Section 7.2 The Math Class Revisited
6
// Java0701.java // This program reviews using class methods & demonstrates the available <Math> class methods & data fields. public class Java0701 { public static void main (String args[]) double halfPI = Math.PI / 2; double quarterPI = Math.PI / 4; System.out.println("The value of E is " + Math.E); System.out.println("The value of PI is " + Math.PI); System.out.println("The absolute value of (-25) is " + Math.abs(-25)); System.out.println("The square root of (1024) is " + Math.sqrt(1024)); System.out.println("( ) rounded up is " + Math.ceil( )); System.out.println("( ) rounded down is " + Math.floor( )); System.out.println("( ) rounded normally is " + Math.round( )); System.out.println("( ) rounded normally is " + Math.round( )); System.out.println("The log base 10 of (100) is " + Math.log10(100)); System.out.println("The natural log of (100) is " + Math.log(100)); System.out.println("The antilog of ( ) is " + Math.exp( )); System.out.println("With (1000,999) the greater number is " + Math.max(1000,999)); System.out.println("With (1000,999) the lesser number is " + Math.min(1000,999)); System.out.println("4 to the 3rd power is " + Math.pow(4,3)); System.out.println("3 to the 4th power is " + Math.pow(3,4)); System.out.println("The sine of (PI/2) is " + Math.sin(halfPI)); System.out.println("The cosine of (PI) is " + Math.cos(Math.PI)); System.out.println("The tangent of (PI/4) is " + Math.tan(quarterPI)); System.out.println("The arcsine of (1) is " + Math.asin(1)); System.out.println("The arccosine of (-1) is " + Math.acos(-1)); System.out.println("The arctangent of (1) is " + Math.atan(1)); System.out.println("(PI) radians equals " + Math.toDegrees(Math.PI) + " degrees"); System.out.println("(180) degrees equals " + Math.toRadians(180) + " radians"); System.out.println("A random real number between 0 & 1 is " + Math.random()); System.out.println("Another random real# between 0 & 1 is " + Math.random()); System.out.println(); }
7
The value of E is The value of PI is The absolute value of (-25) is The square root of (1024) is ( ) rounded up is ( ) rounded down is ( ) rounded normally is ( ) rounded normally is The log base 10 of (100) is The natural log of (100) is The antilog of ( ) is With (1000,999) the greater number is 1000 With (1000,999) the lesser number is 999 4 to the 3rd power is 3 to the 4th power is The sine of (PI/2) is The cosine of (PI) is The tangent of (PI/4) is The arcsine of (1) is The arccosine of (-1) is The arctangent of (1) is (PI) radians equals degrees (180) degrees equals radians A random real number between 0 & 1 is Another random real# between 0 & 1 is
8
Additional Math Class Methods (not previously shown in Chapter 4)
Math.log10(p) returns the log base 10 of p Math.log(p) returns the natural log (base e) of p Math.exp(p) returns the antilog of the p or ep Math.sin(p) returns the trigonometric sine of p Math.cos(p) returns the trigonometric cosine of p Math.tan(p) returns the trigonometric tangent of p Math.asin(p) returns the trigonometric arcsine of p Math.acos(p) returns the trigonometric arccosine of p Math.atan(p) returns the trigonometric arctangent of p Math.toDegrees(p) returns the number of degrees in p radians Math.toRadians(p) returns the number of radians in p degrees Math.random() returns a random real number between 0 & 1
9
Section 7.3 Modular Programming & User Created Methods
10
Modular Programming One Task, One Module
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
11
Kathy Smith 7003 Orleans Court Kensington, Md. 20795 // Java0702.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 Java0702 { public static void main(String[] args) System.out.println("Kathy Smith"); System.out.println("7003 Orleans Court"); System.out.println("Kensington, Md "); } Kathy Smith 7003 Orleans Court Kensington, Md
12
Java0703.fullName(); Kathy Smith Java0703.street(); 7003 Orleans Court
// Java0703.java // This program introduces user-created class methods. The three program statements // of the Java0703.java program are now divided into three user-created methods. // Each method is called with the class-dot-method format. public class Java0703 { public static void main(String[] args) Java0703.fullName(); Java0703.street(); Java0703.cityStateZip(); } 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 "); } Kathy Smith 7003 Orleans Court Kensington, Md
13
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"); }
14
fullName(); street(); cityStateZip(); Kathy Smith 7003 Orleans Court
// Java0704.java // This program example displays the same output as the previous program. // This time the methods are called directly without using the class identifier. // Omitting the class identifier is possible because all the methods are // encapsulated in the same class, <Java0704>. public class Java0704 { public static void main(String[] args) fullName(); street(); cityStateZip(); } 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 "); } Kathy Smith 7003 Orleans Court Kensington, Md
15
class Address // Java0705.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 <Java0704> class. public class Java0705 { public static void main(String args[]) fullName(); street(); cityStateZip(); } 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 "); }
16
Kathy Smith 7003 Orleans Court Kensington, Md. 20795
// Java0706.java // This program cures the problem of the previous program. 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 Java0706 { public static void main(String args[]) Address.fullName(); Address.street(); Address.cityStateZip(); } 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 "); } Kathy Smith 7003 Orleans Court Kensington, Md
17
Only the class with the same name as the file uses public.
// Java0706.java // This program cures the problem of the previous program. 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 Java0706 { public static void main(String args[]) Address.fullName(); Address.street(); Address.cityStateZip(); } 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 "); } NOTE: The 2nd class does NOT use the keyword public. Only the class with the same name as the file uses public.
18
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. If a file has more than one class, only the class with the same name as the file is declared public.
19
File Names & Class Names Review
The external file name of your program must be identical to the public class name inside your program, minus the java extension. For example: If you use public class Howdy in your program then you must save the program with file name Howdy.java
20
Kathy Smith 7003 Orleans Court Kensington, Md. 20795
// Java0707.java // In this program, the <Address> class is in the file Address.java // If the compiler does not find a class it needs in this file, // if will look for it in a .java file with the same name. // This is the whole reason why the name of the file must match the // name of the public class. // NOTE: This class contains the <main> method. // That makes this the "Driving Class" of the program. // That means this is the file that needs to be compiled and executed. public class Java0707 { public static void main(String args[]) Address.fullName(); Address.street(); Address.cityStateZip(); } Kathy Smith 7003 Orleans Court Kensington, Md
21
public class Address // Address.java
// This is the <Address> class used by Java0707.java // NOTE: Now that <Address> is in its own file, it must be declared <public>. // ALSO: This file can be compiled, but since it has not <main> method, it cannot be executed. public 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 ");
22
Program Note While it is proper programming style to put each class in its own file, most program examples in this textbook will continue to put all classes in the same file for simplicity.
23
Section 7.4 Graphics Programs with Multiple Methods
24
NOTE: This is NOT Good Program Design.
// Java0708.java // This program draws a house by placing all the necessary program statements in the <paint> method. public class Java0708 extends Applet { public void paint(Graphics g) g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100); g.setColor(Color.red); g.drawLine(200,200,350,100); g.drawLine(500,200,350,100); g.drawLine(200,200,500,200); g.drawLine(420,146,420,80); g.drawLine(420,80,450,80); g.drawLine(450,80,450,166); g.setColor(Color.black); g.drawRect(330,340,40,60); g.drawOval(340,350,20,40); g.fillOval(364,370,5,5); g.drawRect(220,220,60,60); g.drawLine(220,250,280,250); g.drawLine(250,220,250,280); g.drawRect(420,220,60,60); g.drawLine(420,250,480,250); g.drawLine(450,220,450,280); g.drawRect(320,220,60,60); g.drawLine(320,250,380,250); g.drawLine(350,220,350,280); g.drawRect(220,320,60,60); g.drawLine(220,350,280,350); g.drawLine(250,320,250,380); g.drawRect(420,320,60,60); g.drawLine(420,350,480,350); g.drawLine(450,320,450,380); } NOTE: This is NOT Good Program Design.
25
// Java0709.java // This program organizes all the program // statements of the previous program into six // separate methods. This is better program design. // It is now easier to debug and alter the program. public class Java0709 extends Applet { public void paint(Graphics g) drawFloors(g); drawRoof(g); drawDoor(g); drawWindows(g); drawChimney(g); } public static void drawFloors(Graphics g) g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100); public static void drawRoof(Graphics g) g.setColor(Color.red); g.drawLine(200,200,350,100); g.drawLine(500,200,350,100); g.drawLine(200,200,500,200); public static void drawDoor(Graphics g) g.setColor(Color.black); g.drawRect(330,340,40,60); g.drawOval(340,350,20,40); g.fillOval(364,370,5,5); public static void drawWindows(Graphics g) g.drawRect(220,220,60,60); g.drawLine(220,250,280,250); g.drawLine(250,220,250,280); g.drawRect(420,220,60,60); g.drawLine(420,250,480,250); g.drawLine(450,220,450,280); g.drawRect(320,220,60,60); g.drawLine(320,250,380,250); g.drawLine(350,220,350,280); g.drawRect(220,320,60,60); g.drawLine(220,350,280,350); g.drawLine(250,320,250,380); g.drawRect(420,320,60,60); g.drawLine(420,350,480,350); g.drawLine(450,320,450,380); public static void drawChimney(Graphics g) g.drawLine(420,146,420,80); g.drawLine(420,80,450,80); g.drawLine(450,80,450,166);
26
// Java0710.java // This program places the six methods from the // previous program into their own <House> class, // which is even better program design. public class Java0710 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) g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100); public static void drawRoof(Graphics g) g.setColor(Color.red); g.drawLine(200,200,350,100); g.drawLine(500,200,350,100); g.drawLine(200,200,500,200); public static void drawDoor(Graphics g) g.setColor(Color.black); g.drawRect(330,340,40,60); g.drawOval(340,350,20,40); g.fillOval(364,370,5,5); public static void drawWindows(Graphics g) g.drawRect(220,220,60,60); g.drawLine(220,250,280,250); g.drawLine(250,220,250,280); g.drawRect(420,220,60,60); g.drawLine(420,250,480,250); g.drawLine(450,220,450,280); g.drawRect(320,220,60,60); g.drawLine(320,250,380,250); g.drawLine(350,220,350,280); g.drawRect(220,320,60,60); g.drawLine(220,350,280,350); g.drawLine(250,320,250,380); g.drawRect(420,320,60,60); g.drawLine(420,350,480,350); g.drawLine(450,320,450,380); public static void drawChimney(Graphics g) g.drawLine(420,146,420,80); g.drawLine(420,80,450,80); g.drawLine(450,80,450,166);
27
class Tree Tree.drawTrunk(g); Tree.drawLeaves(g); // Java0711.java
// This program shows that a program can // consist of multiple classes, // each of which containing multiple methods. import java.awt.*; import java.applet.*; public class Java0711 extends Applet { public void paint(Graphics g) House.drawFloors(g); House.drawRoof(g); House.drawDoor(g); House.drawWindows(g); House.drawChimney(g); Tree.drawTrunk(g); Tree.drawLeaves(g); } class House // same as the previous program class Tree public static void drawTrunk(Graphics g) g.setColor(new Color(150,100,15)); // brown g.fillRect(700,400,50,200); public static void drawLeaves(Graphics g) g.setColor(Color.green); g.fillOval(620,195,210,210);
29
Background.drawSky(g); Background.drawGrass(g); class Background
// Java0712.java // This program adds a <Background> class // to draw the "sky" and "grass". // When you run the program, all you see is the // background. // This is because the background was drawn // after, and therefore on top of everything else. import java.awt.*; import java.applet.*; public class Java0712 extends Applet { public void paint(Graphics g) House.drawFloors(g); House.drawRoof(g); House.drawDoor(g); House.drawWindows(g); House.drawChimney(g); Tree.drawTrunk(g); Tree.drawLeaves(g); Background.drawSky(g); Background.drawGrass(g); } class Background public static void drawSky(Graphics g) g.setColor(new Color(128,128,255)); // light blue g.fillRect(0,0,1000,325); public static void drawGrass(Graphics g) g.setColor(new Color(0,128,0)); // dark green g.fillRect(0,325,1000,650); } class House // same as the previous program class Tree
31
Background.drawSky(g); Background.drawGrass(g); class Background
// Java0713.java // This program fixes the issue of the previous // program by drawing the background first. // The house does not look right because we // can see the background through it. // Unlike the tree, the house is not solid. import java.awt.*; import java.applet.*; public class Java0713 extends Applet { public void paint(Graphics g) Background.drawSky(g); Background.drawGrass(g); House.drawFloors(g); House.drawRoof(g); House.drawDoor(g); House.drawWindows(g); House.drawChimney(g); Tree.drawTrunk(g); Tree.drawLeaves(g); } class Background public static void drawSky(Graphics g) g.setColor(new Color(128,128,255)); // light blue g.fillRect(0,0,1000,325); public static void drawGrass(Graphics g) g.setColor(new Color(0,128,0)); // dark green g.fillRect(0,325,1000,650); } class House // same as the previous program class Tree
33
// Java0714.java // This program changes the methods of the // <House> class so they draw solid shapes. // Now the drawing appears as it was intended. import java.awt.*; import java.applet.*; public class Java0714 extends Applet { public void paint(Graphics g) Background.drawSky(g); Background.drawGrass(g); House.drawFloors(g); House.drawRoof(g); House.drawDoor(g); House.drawWindows(g); House.drawChimney(g); Tree.drawTrunk(g); Tree.drawLeaves(g); } class Background // same as the previous program class Tree // House class on next slide…
34
class House { public static void drawFloors(Graphics g) g.setColor(new Color(231,198,154)); // light tan g.fillRect(200,200,300,200); g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100); } public static void drawRoof(Graphics g) g.setColor(Color.red); Polygon roof = new Polygon(); roof.addPoint(200,200); roof.addPoint(350,100); roof.addPoint(500,200); g.fillPolygon(roof); public static void drawDoor(Graphics g) g.fillRect(330,340,40,60); g.setColor(Color.black); g.drawRect(330,340,40,60); g.drawOval(340,350,20,40); g.fillOval(364,370,5,5); public static void drawWindows(Graphics g) g.setColor(Color.white); g.fillRect(220,220,60,60); g.fillRect(420,220,60,60); g.fillRect(320,220,60,60); g.fillRect(220,320,60,60); g.fillRect(420,320,60,60); g.drawRect(220,220,60,60); g.drawLine(220,250,280,250); g.drawLine(250,220,250,280); g.drawRect(420,220,60,60); g.drawLine(420,250,480,250); g.drawLine(450,220,450,280); g.drawRect(320,220,60,60); g.drawLine(320,250,380,250); g.drawLine(350,220,350,280); g.drawRect(220,320,60,60); g.drawLine(220,350,280,350); g.drawLine(250,320,250,380); g.drawRect(420,320,60,60); g.drawLine(420,350,480,350); g.drawLine(450,320,450,380); public static void drawChimney(Graphics g) Polygon chimney = new Polygon(); chimney.addPoint(420,146); chimney.addPoint(420,80); chimney.addPoint(450,80); chimney.addPoint(450,166); g.fillPolygon(chimney);
36
// This program has each class in its own file.
// Java0715.java // This program has each class in its own file. // It also demonstrates the good organizational practice of // putting all files for a particular program in the same folder. // NOTE: This class contains the <paint> method. // That makes this the "Driving Class" of the program. // That means this is the file that needs to be compiled. import java.awt.*; import java.applet.*; public class Java0715 extends Applet { public void paint(Graphics g) Background.drawSky(g); Background.drawGrass(g); House.drawFloors(g); House.drawRoof(g); House.drawDoor(g); House.drawWindows(g); House.drawChimney(g); Tree.drawTrunk(g); Tree.drawLeaves(g); }
37
public class House // House.java import java.awt.*;
import java.awt.*; import java.applet.*; public class House { public static void drawFloors(Graphics g) g.setColor(new Color(231,198,154)); // light tan g.fillRect(200,200,300,200); g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100); } public static void drawRoof(Graphics g) g.setColor(Color.red); Polygon roof = new Polygon(); roof.addPoint(200,200); roof.addPoint(350,100); roof.addPoint(500,200); g.fillPolygon(roof); public static void drawDoor(Graphics g) g.fillRect(330,340,40,60); g.setColor(Color.black); g.drawRect(330,340,40,60); g.drawOval(340,350,20,40); g.fillOval(364,370,5,5); public static void drawWindows(Graphics g) g.setColor(Color.white); g.fillRect(220,220,60,60); g.fillRect(420,220,60,60); g.fillRect(320,220,60,60); g.fillRect(220,320,60,60); g.fillRect(420,320,60,60); g.drawRect(220,220,60,60); g.drawLine(220,250,280,250); g.drawLine(250,220,250,280); g.drawRect(420,220,60,60); g.drawLine(420,250,480,250); g.drawLine(450,220,450,280); g.drawRect(320,220,60,60); g.drawLine(320,250,380,250); g.drawLine(350,220,350,280); g.drawRect(220,320,60,60); g.drawLine(220,350,280,350); g.drawLine(250,320,250,380); g.drawRect(420,320,60,60); g.drawLine(420,350,480,350); g.drawLine(450,320,450,380); public static void drawChimney(Graphics g) Polygon chimney = new Polygon(); chimney.addPoint(420,146); chimney.addPoint(420,80); chimney.addPoint(450,80); chimney.addPoint(450,166); g.fillPolygon(chimney);
38
public class Background public class Tree
// Background.java import java.awt.*; import java.applet.*; public class Background { public static void drawSky(Graphics g) g.setColor(new Color(128,128,255)); // light blue g.fillRect(0,0,1000,325); } public static void drawGrass(Graphics g) g.setColor(new Color(0,128,0)); // dark green g.fillRect(0,325,1000,650); } // Tree.java public class Tree public static void drawTrunk(Graphics g) g.setColor(new Color(150,100,15)); // brown g.fillRect(700,400,50,200); public static void drawLeaves(Graphics g) g.setColor(Color.green); g.fillOval(620,195,210,210);
39
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. These modules are called methods in Java. Object Oriented Design continues by placing modules of a common nature into a separate class. When a program has multiple classes, it is very common to put each class in its own file – one whose name matches the name of the class.
40
Section 7.5 Creating a Big Graphics Program Step-By-Step
41
// Step 1 – Create the <paint> method.
// Java0716.java // Beginning a Big Graphics Program. // Step 1 – Create the <paint> method. // This first step will not compile because the program // is attempting to call methods which do not exist. import java.awt.*; import java.applet.*; public class Java0716 extends Applet { public void paint(Graphics g) drawFloors(g); drawRoof(g); drawDoor(g); drawWindows(g); drawChimney(g); }
42
// Step 1 – Create the <paint> method.
// Java0716.java // Beginning a Big Graphics Program. // Step 1 – Create the <paint> method. // This first step will not compile because the program // is attempting to call methods which do not exist. import java.awt.*; import java.applet.*; public class Java0716 extends Applet { public void paint(Graphics g) drawFloors(g); drawRoof(g); drawDoor(g); drawWindows(g); drawChimney(g); }
43
// Step 2 – Create Stubs. // Java0717.java
// Beginning a Big Graphics Program // Step 2 – Create Stubs. // Stubs are methods with nothing // between the braces { }. // With the stubs in place, the // program can compile. import java.awt.*; import java.applet.*; public class Java0717 extends Applet { public void paint(Graphics g) drawFloors(g); drawRoof(g); drawDoor(g); drawWindows(g); drawChimney(g); } public static void drawFloors(Graphics g) public static void drawRoof(Graphics g) public static void drawDoor(Graphics g) public static void drawWindows(Graphics g) public static void drawChimney(Graphics g)
45
// Beginning a Big Graphics Program // Step 3 – Write the first
// Java0718.java // Beginning a Big Graphics Program // Step 3 – Write the first // method and make sure // it works. import java.awt.*; import java.applet.*; public class Java0718 extends Applet { public void paint(Graphics g) drawFloors(g); drawRoof(g); drawDoor(g); drawWindows(g); drawChimney(g); } public static void drawFloors(Graphics g) g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100); public static void drawRoof(Graphics g) public static void drawDoor(Graphics g) public static void drawWindows(Graphics g) public static void drawChimney(Graphics g)
47
// Beginning a Big Graphics Program // Step 4 – Write the next
// Java0719.java // Beginning a Big Graphics Program // Step 4 – Write the next // method and make sure // it works. import java.awt.*; import java.applet.*; public class Java0719 extends Applet { public void paint(Graphics g) drawFloors(g); drawRoof(g); drawDoor(g); drawWindows(g); drawChimney(g); } public static void drawFloors(Graphics g) g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100); public static void drawRoof(Graphics g) g.setColor(Color.red); g.drawLine(200,200,350,100); g.drawLine(500,200,350,100); g.drawLine(200,200,500,200); public static void drawDoor(Graphics g) public static void drawWindows(Graphics g) public static void drawChimney(Graphics g)
49
// Step 5 – Repeat step 4 until // the entire program is done.
// Java0720.java // Beginning a Big Graphics Program // Step 5 – Repeat step 4 until // the entire program is done. public class Java0720 extends Applet { public void paint(Graphics g) drawFloors(g); drawRoof(g); drawDoor(g); drawWindows(g); drawChimney(g); } public static void drawFloors(Graphics g) g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100); public static void drawRoof(Graphics g) g.setColor(Color.red); g.drawLine(200,200,350,100); g.drawLine(500,200,350,100); g.drawLine(200,200,500,200); public static void drawDoor(Graphics g) g.setColor(Color.black); g.drawRect(330,340,40,60); g.drawOval(340,350,20,40); g.fillOval(364,370,5,5); public static void drawWindows(Graphics g) g.drawRect(220,220,60,60); g.drawLine(220,250,280,250); g.drawLine(250,220,250,280); g.drawRect(420,220,60,60); g.drawLine(420,250,480,250); g.drawLine(450,220,450,280); g.drawRect(320,220,60,60); g.drawLine(320,250,380,250); g.drawLine(350,220,350,280); g.drawRect(220,320,60,60); g.drawLine(220,350,280,350); g.drawLine(250,320,250,380); g.drawRect(420,320,60,60); g.drawLine(420,350,480,350); g.drawLine(450,320,450,380); public static void drawChimney(Graphics g) g.drawLine(420,146,420,80); g.drawLine(420,80,450,80); g.drawLine(450,80,450,166);
51
Section 7.6 Void Methods with a Single Parameter
52
Method Calls With Parameters
Parameter method example: double result1 = Math.sqrt(100); double result2 = Math.pow(2,5); g.drawLine(400,225,600,425); g.setColor(new Color(150,100,15)); Scanner input = new Scanner(System.in);
53
Method Calls Without Parameters
Non-Parameter method examples: String name = input.nextLine(); int age = input.nextInt( ); double gpa = input.nextDouble(); Address.fullName( ); Address.street( ); Address.cityStateZip( );
54
Overloaded Method Calls
Overloaded method examples: System.out.println("Hello World"); System.out.println( ); You will learn more overloaded methods starting with the net chapter.
55
The parameter value is 100 // Java0721.java
// This program sends a value to a parameter method and then // displays the value of the parameter. public class Java0721 { public static void main(String args[]) displayParameter(100); } public static void displayParameter(int number) System.out.println(); System.out.println("The parameter value is " + number); The parameter value is 100
56
Parameters Terminology
Actual Parameters The parameters in the method call. This is the actual information that you are sending to the method. Formal Parameters The parameters in the method heading. This is the formal declaration of the parameters. Here their form is determined. displayParameter(100); public static void displayParameter(int number)
57
displayParameter(x); displayParameter(20 + 30);
// Java0722.java // This program demonstrates that the calling parameter can be: // a constant, like 13 or Math.PI, a variable, like x, // an expression with constants and/or variables, like and x + 5, // and a call to a method, which returns a value, like Math.sqrt(100). public class Java0722 { public static void main(String args[]) double x = 100.0; displayParameter(13); displayParameter(x); displayParameter( ); displayParameter(x + 5); displayParameter(Math.PI); displayParameter(Math.sqrt(225)); } public static void displayParameter(double number) System.out.println("The parameter value is " + number); System.out.println(); The parameter value is 13.0 The parameter value is 100.0 The parameter value is 50.0 The parameter value is 105.0 The parameter value is The parameter value is 15.0
58
Actual Parameter Formats
Actual parameters can be: constants (13) or (Math.PI) variables (x) expressions with constants only ( ) expressions with variables & constants (x + 3) return method calls (Math.sqrt(225))
59
The Football Analogy The Quarterback - The Actual Parameter
The Football - A copy of the data The actual parameters pass the data to the formal parameters. The Receiver - Formal Parameter displayParameter(x); showArea 100 public static void displayParameter(double number)
60
Section 7.7 Void Methods with Multiple Parameters
61
The rectangle area is 5000 int area = L * W; // Java0723.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 Java0723 { public static void main(String args[]) int length = 100; int width = 50; showArea(length, width); showArea(width, length); } public static void showArea(int L, int W) System.out.println(); int area = L * W; System.out.println("The rectangle area is " + area); The rectangle area is 5000
62
Remember, Parameter sequence is important!
// Java0724.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 Java0724 { public static void main(String args[]) int num1 = 100; int num2 = 50; showDifference(num1, num2); showDifference(num2, num1); } public static void showDifference(int a, int b) System.out.println(); int difference = a – b; System.out.println("The difference is " + difference); The difference is 50 The difference is -50 Remember, Parameter sequence is important!
63
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.
64
showDifference(int num1, int num2); // Line 1
// Java0725.java // This program demonstrates 2 common mistakes made by students. // The "Line 1" error is caused by defining variables in the method call. // The "Line 2" error is caused by not giving the 2nd formal parameter a data type. public class Java0725 { public static void main(String args[]) showDifference(int num1, int num2); // Line 1 } public static void showDifference(int a, b) // Line 2 System.out.println(); int difference = a - b; System.out.println("The difference is " + difference);
65
Common Parameters 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)
66
Remove the comment and re-compile.
// Java0726.java // This program demonstrates that multiple parameters may be // different data types. Parameter sequence is very important. public class Java0726 { public static void main(String args[]) multiTypeDemo("Hans",30,3.575); // 3 different type parameters method call // multiTypeDemo(30,3.575,"Hans"); // same parameters, but in the wrong order } 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); This method has 3 parameters with three different types Name: Hans Age: 30 GPA: Try This: Remove the comment and re-compile.
67
With the parameters in the wrong order, the program cannot compile.
// Java0725.java // This program demonstrates that multiple parameters may be // different data types. Parameter sequence is very important. public class Java0725 { public static void main(String args[]) multiTypeDemo("Hans",30,3.575); // 3 different type parameters method call multiTypeDemo(30,3.575,"Hans"); // same parameters, but in the wrong order } 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); With the parameters in the wrong order, the program cannot compile.
68
Parameter Rules The actual parameters and the formal parameters must match in these 3 ways: 1. They must be the same quantity. 2. They must be the same type. 3. They must be the same sequence.
69
The Track Relay Analogy – Race 1
US GB FR NL The second runner from the Netherlands is missing. The number of actual parameters and formal parameters do not match.
70
The Track Relay Analogy – Race 2
US GB FR NL The second runners from the Netherlands and France are in the wrong lane. The formal parameters are not in the same order as the actual parameters. They must correspond.
71
The Track Relay Analogy – Race 3
US (John) US (Greg) GB (Charles) GB (William) FR (Gerald) FR (Louis) NL (Hans) The runners are in proper staring position. The parameters correspond. The fact that there are 2 people from the Netherlands with the same name is not a problem.
72
Important Rules About Using Parameters with Methods
The number of parameters in the method call (actual parameters) must match the number of parameters in the method heading (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 identifiers of the actual parameters may be the same as or different from the identifiers of the formal parameters.
73
Section 7.8 Return Methods with a Single Parameter
74
public static int getNextNumber(int n) n++; return n;
// Java0727.java // This program introduces a return method with one parameter. // Method <getNextNumber> returns the next integer value of its parameter. public class Java0727 { public static void main(String args[]) for (int k = 1; k <= 10; k++) int rnd = Expo.random(10,99); System.out.println("Random number: " + rnd); System.out.println("Next number : " + getNextNumber(rnd)); } System.out.println(); public static int getNextNumber(int n) n++; return n; Random number: 73 Next number : 74 Random number: 21 Next number : 22 Random number: 15 Next number : 16 Random number: 22 Next number : 23 Random number: 69 Next number : 70 Random number: 13 Next number : 14 Random number: 39 Next number : 40 Random number: 24 Next number : 25 Random number: 78 Next number : 79
75
public static boolean checkPIN(int pin) boolean temp = (pin == 1234);
// Java0728.java // This example returns a boolean value, which is used // frequently to check for correct user keyboard input. public class Java0728 { public static void main(String args[]) boolean okPIN = false; do System.out.print("Enter your four-digit PIN ===>> "); int pin = Expo.enterInt(); okPIN = checkPIN(pin); System.out.println(); } while (!okPIN); System.out.println("Select your bank transaction:"); public static boolean checkPIN(int pin) boolean temp = (pin == 1234); return temp; Enter your four-digit PIN ===>> 4600 Enter your four-digit PIN ===>> 6623 Enter your four-digit PIN ===>> 7577 Enter your four-digit PIN ===>> 1234 Select your bank transaction:
76
Section 7.9 Return Methods with Multiple Parameters
77
1000 + 100 = 1100 // Java0729.java // There are two differences:
// This program demonstrates the difference between a void <add1> method & 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 Java0729 { public static void main(String args[]) int nbr1 = 1000; int nbr2 = 100; add1(nbr1,nbr2); System.out.println(nbr1 + " + " + nbr2 + " = " + add2(nbr1,nbr2)); } public static void add1(int n1, int n2) int sum = n1 + n2; System.out.println(n1 + " + " + n2 + " = " + sum); public static int add2(int n1, int n2) return sum; = 1100
78
// Java0730.java // This program demonstrates how to create a four-function <Calculator> class // with return methods. public class Java0730 { public static void main(String args[]) int nbr1 = 1000; int nbr2 = 100; System.out.println(nbr1 + " + " + nbr2 + " = " + Calculator.add(nbr1,nbr2)); System.out.println(nbr1 + " - " + nbr2 + " = " + Calculator.subtract(nbr1,nbr2)); System.out.println(nbr1 + " * " + nbr2 + " = " + Calculator.multiply(nbr1,nbr2)); System.out.println(nbr1 + " / " + nbr2 + " = " + Calculator.divide(nbr1,nbr2)); System.out.println(); } class Calculator public static int add(int n1, int n2) { return n1 + n2; } public static int subtract(int n1, int n2) { return n1 - n2; } public static int multiply(int n1, int n2) { return n1 * n2; } public static int divide(int n1, int n2) { return n1 / n2; } = 1100 = 900 1000 * 100 = 1000 / 100 = 10
79
Sum: 500 Sum: 900 Let's go shopping!
// Java0731.java // This program reviews different ways to call a return method. public class Java0731 { public static void main(String args[]) System.out.println("Sum: " + add(200,300)); int sum = add(400,500); System.out.println("Sum: " + sum); int checking = 600; int savings = 700; if (add(checking,savings) <= 0) System.out.println("You are broke!"); else System.out.println("Let's go shopping!"); } public static int add(int n1, int n2) int sum = n1 + n2; return sum; Sum: 500 Sum: 900 Let's go shopping!
80
Section 7.10 Introduction to Program Design
81
The Payroll Case Study You are about to study
8 stages of a case study. This is the one of many case studies that you will work with. The first program will be very simplistic and each program will make some small change or add something new.
82
// even to the degree that there is no program indentation.
// Java0732.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.*;import java.util.Scanner;public class Java0732{ 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");Scanner n = new Scanner(System.in);System.out.println("\nPAYROLL CASE STUDY #1\n");System.out.print( "Enter Name ===>> ");a = n.nextLine();System.out.print("Enter Hours Worked ===>> "); b = n.nextInt();System.out.print("Enter Hourly Rate ===>> ");c = n.nextInt();System.out.print( "Enter Dependents ===>> ");d = n.nextInt(); 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");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");}}
83
This is the output for most of the programs in the
PAYROLL CASE STUDY #1 Enter Name ===>> Tom Jones Enter Hours Worked ===>> 49 Enter Hourly Rate ===>> 8.75 Enter Dependents ===>> 3 Name: Tom Jones Hourly rate: $8.75 Hours worked: 49.0 Dependents: 3 Tax rate: % Regular pay: $350.00 Overtime pay: $118.12 Gross pay: $468.12 Deductions: $72.56 Net pay: $395.57 This is the output for most of the programs in the Payroll Case Study.
84
// Java0733.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.*; import java.util.Scanner; public class Java0733 { 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"); Scanner n = new Scanner(System.in); System.out.println("\nPAYROLL CASE STUDY #2\n"); System.out.print("Enter Name ===>> "); a = n.nextLine(); System.out.print("Enter Hours Worked ===>> "); b = n.nextInt(); System.out.print("Enter Hourly Rate ===>> "); c = n.nextInt(); System.out.print("Enter Dependents ===>> "); d = n.nextInt();
85
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;
86
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)); }
87
// Java0734.java // Payroll Case Study #3 // Stage 3 improves program readability by using meaningful identifiers. import java.text.*; import java.util.Scanner; public class Java0734 { 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"); Scanner input = new Scanner(System.in); System.out.println("\nPAYROLL CASE STUDY #3\n");
88
System.out.print("Enter Name ===>> ");
employeeName = input.nextLine(); System.out.print("Enter Hours Worked ===>> "); hoursWorked = input.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); hourlyRate = input.nextDouble(); System.out.print("Enter Dependents ===>> "); numDependents = input.nextInt(); if (hoursWorked > 40) { overtimeHours = hoursWorked - 40; regularPay = 40 * hourlyRate; overtimePay = overtimeHours * hourlyRate * 1.5; } else regularPay = hoursWorked * hourlyRate; overtimePay = 0; grossPay = regularPay + overtimePay;
89
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: " + 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));
90
// Java0735.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. import java.text.*; // used for text output with <DecimalFormat> class. import java.util.Scanner; // used for text/number input with the <Scanner> class. public class Java0735 { 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 dependents 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 //////////////////////////////////////////////////////////////////////////////////////////////////////
91
///////////////////////////////////////////////////////////////////////////////////////////////////// // Program object // DecimalFormat money = new DecimalFormat("$0.00"); // money is used to display values in monetary format. Scanner input = new Scanner(System.in); // input is used to enter the employee data. //////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // Program input System.out.println("\nPAYROLL CASE STUDY #4\n"); System.out.print("Enter Name ===>> "); employeeName = input.nextLine(); System.out.print("Enter Hours Worked ===>> "); hoursWorked = input.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); hourlyRate = input.nextDouble(); System.out.print("Enter Dependents ===>> "); numDependents = input.nextInt(); //////////////////////////////////////////////////////////////////////////////////////////////////
92
// Program computation //
////////////////////////////////////////////////////////////////////////////////////////////////// // 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; 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 the number of declared dependents
93
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)); }
94
// Java0736.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.*; import java.util.Scanner; public class Java0736 { 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"); Scanner input = new Scanner(System.in); System.out.println("\nPAYROLL CASE STUDY #5\n"); enterData(); computeGrosspay(); computeDeductions(); computeNetpay(); printCheck(); }
95
public static void enterData() {
System.out.print("Enter Name ===>> "); employeeName = input.nextLine(); System.out.print("Enter Hours Worked ===>> "); hoursWorked = input.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); hourlyRate = input.nextDouble(); System.out.print("Enter Dependents ===>> "); numDependents = input.nextInt(); } 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; }
96
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;
97
public static void printCheck()
{ 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)); }
98
The user-defined methods cannot find the variables because they are all declared inside the main method. : : : : : : :
99
// Java0737.java // Payroll Case Study #6 // Stage #6 fixes the problem from Stage 5 by using class variables. // NOTE: The <input> and <money> objects are defined locally in the // <enterData> and <printCheck> methods respectively because // both objects are only accessed by their one respective method. import java.text.*; import java.util.Scanner; public class Java0737 { static String employeeName; static double hoursWorked; static double hourlyRate; static int numdependents; static double overtimeHours; static double regularPay; static double overtimePay; static double taxRate; static double grossPay; static double taxDeductions; static double netPay;
100
When done properly, should look like an outline for your program.
public static void main (String args[]) { System.out.println("\nPAYROLL CASE STUDY #6\n"); enterData(); computeGrosspay(); computeDeductions(); computeNetpay(); printCheck(); } public static void enterData() Scanner input = new Scanner(System.in); System.out.print("Enter Name ===>> "); employeeName = input.nextLine(); System.out.print("Enter Hours Worked ===>> "); hoursWorked = input.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); hourlyRate = input.nextDouble(); System.out.print("Enter Dependents ===>> "); numDependents = input.nextInt(); When done properly, the main method should look like an outline for your program.
101
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;
102
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;
103
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)); }
104
Payroll.computeGrosspay(); Payroll.computeDeductions();
// Java0738.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.*; import java.util.Scanner; public class Java0738 { public static void main (String args[]) System.out.println("\nPAYROLL CASE STUDY #7\n"); Payroll.enterData(); Payroll.computeGrosspay(); Payroll.computeDeductions(); Payroll.computeNetpay(); Payroll.printCheck(); }
105
class Payroll { static String employeeName; static double hoursWorked;
static double hourlyRate; static int numdependents; static double overtimeHours; static double regularPay; static double overtimePay; static double taxRate; static double grossPay; static double taxDeductions; static double netPay; public static void enterData() Scanner input = new Scanner(System.in); System.out.print("Enter Name ===>> "); employeeName = input.nextLine(); System.out.print("Enter Hours Worked ===>> "); hoursWorked = input.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); hourlyRate = input.nextDouble(); System.out.print("Enter Dependents ===>> "); numDependents = input.nextInt(); }
106
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;
107
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;
108
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)); }
109
// Java0739.java // Payroll Case Study #8 // In Stage #8 the driving // class and the <Payroll> // class are each placed // in separate files. public class Java0739 { public static void main (String args[]) System.out.println("\nPAYROLL CASE STUDY #8\n"); Payroll.enterData(); Payroll.computeGrosspay(); Payroll.computeDeductions(); Payroll.computeNetpay(); Payroll.printCheck(); }
110
// Payroll.java import java.text.*; import java.util.Scanner; public class Payroll { static String employeeName; static double hoursWorked; static double hourlyRate; static int numDependents; static double overtimeHours; static double regularPay; static double overtimePay; static double taxRate; static double grossPay; static double taxDeductions; static double netPay; public static void enterData() Scanner input = new Scanner(System.in); System.out.print("Enter Name ===>> "); employeeName = input.nextLine(); System.out.print("Enter Hours Worked ===>> "); hoursWorked = input.nextDouble(); The remainder of the Payroll class is the same as the previous program.
111
Local Variables & 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.
112
Program Design Notes This was the first introduction to program design. Additional design features will be introduced as you learn more object-oriented programming. At this stage you can already consider the following: • Programs should use self-commenting identifiers. • Control structures and block structure 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.
113
Section 7.11 Creating Methods with Other Methods
114
picket(g,x); // Java0740.java
// This program demonstrates a <picket> method that will be used to display a fence. import java.awt.*; import java.applet.*; public class Java0740 extends Applet { public void paint(Graphics g) g.setColor(Color.black); g.fillRect(0,0,1000,650); // 2 Cross Beams g.setColor(new Color(210,180,140)); // tan g.fillRect(0,500,1000,25); g.fillRect(0,600,1000,25); // 25 Pickets g.setColor(new Color(150,100,15)); // brown for (int x = 2; x < 1000; x+=40) picket(g,x); } public static void picket(Graphics g, int x) { Polygon picket = new Polygon(); picket.addPoint(x,650); picket.addPoint(x,500); picket.addPoint(x+18,450); picket.addPoint(x+36,500); picket.addPoint(x+36,650); g.fillPolygon(picket); }
116
The Logic of the picket Method
picket(g,x); All graphics methods need g. x is the horizontal value of the bottom left corner of the picket. The y (vertical) value of the bottom left corner is always 650 since all pickets will be at the bottom of the screen. The other 4 coordinates of the picket are relative to the point (x,650). x+18,450 x,500 x+36,500 x,650 x+36,650
117
fence(g); picket(g,x); public static void picket(Graphics g, int x) {
// Java0741.java // This program uses the <picket> method to create the <fence> method. import java.awt.*; import java.applet.*; public class Java0741 extends Applet { public void paint(Graphics g) g.setColor(Color.black); g.fillRect(0,0,1000,650); fence(g); } public static void fence(Graphics g) // 2 Cross Beams g.setColor(new Color(210,180,140)); // tan g.fillRect(0,500,1000,25); g.fillRect(0,600,1000,25); // 25 Pickets g.setColor(new Color(150,100,15)); // brown for (int x = 2; x < 1000; x+=40) picket(g,x); public static void picket(Graphics g, int x) { Polygon picket = new Polygon(); picket.addPoint(x,650); picket.addPoint(x,500); picket.addPoint(x+18,450); picket.addPoint(x+36,500); picket.addPoint(x+36,650); g.fillPolygon(picket); }
118
Section 7.12 Making a Utility Library Class
119
// Utility.java // This file contains useful methods that can be used by several different programs. import java.awt.*; import java.applet.*; public class Utility { public static int random(int min, int max) int range = max - min + 1; int randomNumber = (int)(Math.random() * range) + min; return randomNumber; } public static void setBackground(Graphics g, Color c) g.setColor(c); g.fillRect(0,0,1000,650); public static void setRandomColor(Graphics g) int red = random(0,255); int green = random(0,255); int blue = random(0,255); g.setColor(new Color(red, green, blue));
120
nightSky(g); // Java0742.java
// This program combines many user-defined methods to create a graphics image. // Some of the methods calls are for methods in the <Utility.java> file. import java.awt.*; import java.applet.*; public class Java0742 extends Applet { public void paint(Graphics g) nightSky(g); fence(g); } public static void randomStar(Graphics g) int x = Utility.random(0,996); int y = Utility.random(0,296); Utility.setRandomColor(g); g.fillRect(x,y,3,3); public static void nightSky(Graphics g) Utility.setBackground(g,Color.black); // 100 random stars for (int j = 1; j <= 100; j++) randomStar(g); moon(g); 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) Polygon picket = new Polygon(); picket.addPoint(x,650); picket.addPoint(x,500); picket.addPoint(x+18,450); picket.addPoint(x+36,500); picket.addPoint(x+36,650); g.fillPolygon(picket); public static void fence(Graphics g) // 2 Cross Beams g.setColor(new Color(210,180,140)); // tan g.fillRect(0,500,1000,25); g.fillRect(0,600,1000,25); // 25 Pickets g.setColor(new Color(150,100,15)); // brown for (int x = 2; x < 1000; x+=40) picket(g,x);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.