Exposure Java Slides - Fort Thomas Independent Schools

Exposure Java Slides - Fort Thomas Independent Schools

Exposure Java 201 Chapter 7Edition Slides APCS Creating Class Methods PowerPoint P resentation created by: Mr. John L. M. Schram and Mr. Leon Schram Authors of Ex posure Java Section 7.1 Introduction

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). 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. Section 7.2 The Math Class

Revisited Additional Math Class Methods Math.exp(p) returns the antilog of p, or ep Math.log(p) returns the log (base e) of p 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.toDegrees(p) returns the number of degrees in p radians Math.toRadians(p) returns the number of radians in p degrees // Java0701.java // This program reviews using class methods and demonstrates most of the // available class methods and data fields. public class Java0701 { public static void main (String args[]) { System.out.println("\nJAVA0701.JAVA\n");

System.out.println("The value of E is System.out.println("The value of PI is System.out.println("The absolute value of (-25) is System.out.println("The square root of (1024) is System.out.println("The ceiling of (5.00001) is System.out.println("The floor of (5.99999) is System.out.println("The round of (5.50001) is System.out.println("The antilog of (4.605170185) is System.out.println("The log of (100) is System.out.println("The max of (1000,999) is System.out.println("The min of (1000,999) is System.out.println("The power of (4,3) is System.out.println("The random of () is System.out.println("The sine of (0) is System.out.println("The cosine of (3.141592653) is System.out.println("The tangent of (0.785398163) is System.out.println("The toDegrees of (3.141592653) is

System.out.println("The toRadians of (180) is System.out.println(); } } " + Math.E); " + Math.PI); " + Math.abs(-25)); " + Math.sqrt(1024)); " + Math.ceil(5.00001)); " + Math.floor(5.99999)); " + Math.round(5.50001)); " + Math.exp(4.605170185)); " + Math.log(100)); " + Math.max(1000,999)); " + Math.min(1000,999)); " + Math.pow(4,3));

" + Math.random()); " + Math.sin(0)); " + Math.cos(3.141592653)); " + Math.tan(0.785398163)); " + Math.toDegrees(3.141592653)); " + Math.toRadians(180)); Section 7.3 Modular Programming & User Created Methods 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 // Java0702.java // This program displays a simple mailing address. // It is used to demonstrate how to divide sections in // the main method into multiple user-created methods. public class Java0702 { public static void main(String[] args) { System.out.println("\nJAVA0702.JAVA\n"); System.out.println("Kathy Smith"); System.out.println("7003 Orleans Court"); System.out.println("Kensington, Md. 20795"); System.out.println(); }

} // Java0703.java // This program introduces user-created class methods. // The three class methods are called with the same dot.method syntax // as the methods of the Math class. public class Java0703 { public static void main(String[] args) { System.out.println("\nJAVA0703.JAVA\n"); Java0703.fullName(); Java0703.street(); Java0703.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"); } } // 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) { System.out.println("\nJAVA0704.JAVA\n"); 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"); }

} 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. // Java0705.java // This program demonstrates how to use a second class separate from the // main program class. This program will not compile because the Name, // Street and CityStateZip methods are no longer encapsulated in Java0705. public class Java0705 { public static void main(String args[]) {

System.out.println("\nJAVA0705.JAVA\n"); fullName(); street(); cityStateZip(); System.out.println(); } } class Address { public static void fullName() public static void street() { System.out.println("Kathy Smith"); } { System.out.println("7003 Orleans Court"); } public static void cityStateZip() { System.out.println("Kensington, Md. 20795"); } }

// Java0706.java // The problem of Java0705.java is now fixed. It is possible to declare // multiple classes in one program. However, you must use the dot.method // syntax to call any of the

class methods. public class Java0706 { public static void main(String args[]) { System.out.println("\nJAVA0706.JAVA\n"); Address.fullName(); Address.street(); Address.cityStateZip(); System.out.println(); } } class Address

{ public static void fullName() public static void street() { System.out.println("Kathy Smith"); } { System.out.println("7003 Orleans Court"); } public static void cityStateZip() { System.out.println("Kensington, Md. 20795"); } } // Java0706.java // The problem of Java0705.java is now fixed. It is possible to declare // multiple classes in one program. However, you must use the dot.method // syntax to call any of the

class methods. public class Java0706 { public static void main(String args[])

{ System.out.println("\nJAVA0706.JAVA\n"); Address.fullName(); NOTE: Address.street(); Address.cityStateZip(); The 2nd class does NOT System.out.println(); use the keyword public. } Only the class with the same } class Address { public static void fullName() public static void street()

name as the file uses public. { System.out.println("Kathy Smith"); } { System.out.println("7003 Orleans Court"); } public static void cityStateZip() { System.out.println("Kensington, Md. 20795"); } } // Java0707.java // This program draws a house by placing all the necessary program statements in the method. import java.awt.*; import java.applet.*; public class Java0707 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); NOTE: This is NOT Good Program Design. If you wanted to change the appearance of the door or a window, you would have to figure out which part of the program to edit. // Java0708.java // This program divides all the statements of in the previous program into 5 separate methods public static void drawChimney(Graphics g) import java.awt.*; { import java.applet.*; g.setColor(Color.red); public class Java0708 extends Applet g.drawLine(420,146,420,80);

{ g.drawLine(420,80,450,80); g.drawLine(450,80,450,166); public void paint(Graphics g) } { } g) public static void drawFloors(Graphics { } g)

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); } drawFloors(g); drawRoof(g); drawChimney(g); drawDoor(g); drawWindows(g); g.setColor(Color.blue); g.drawRect(200,200,300,100); g.drawRect(200,300,300,100);

public static void drawRoof(Graphics { } 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 drawWindows(Graphics g) { g.setColor(Color.black); 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); } // Java0709.java This program uses the better program design of creating a separate class,

// which contains the five methods to draw the complete hour program. import java.awt.*; public static void drawChimney(Graphics g) import java.applet.*; { g.setColor(Color.red); public class Java0709 extends Applet g.drawLine(420,146,420,80); { g.drawLine(420,80,450,80); public void paint(Graphics g) g.drawLine(450,80,450,166); { } House.drawFloors(g); public static void drawDoor(Graphics g) House.drawRoof(g);

{ House.drawChimney(g); g.setColor(Color.black); House.drawDoor(g); g.drawRect(330,340,40,60); g.drawOval(340,350,20,40); House.drawWindows(g); g.fillOval(364,370,5,5); } } } public static void drawWindows(Graphics g) class House { { g.setColor(Color.black); public static void drawFloors(Graphics

g.drawRect(220,220,60,60); g) g.drawLine(220,250,280,250); { g.drawLine(250,220,250,280); g.drawRect(420,220,60,60); g.setColor(Color.blue); g.drawLine(420,250,480,250); g.drawRect(200,200,300,100); g.drawLine(450,220,450,280); g.drawRect(200,300,300,100); g.drawRect(320,220,60,60); } g.drawLine(320,250,380,250); g.drawLine(350,220,350,280); g.drawRect(220,320,60,60); public static void drawRoof(Graphics

g.drawLine(220,350,280,350); g) g.drawLine(250,320,250,380); { g.drawRect(420,320,60,60); g.setColor(Color.red); g.drawLine(420,350,480,350); g.drawLine(450,320,450,380); g.drawLine(200,200,350,100); } g.drawLine(500,200,350,100); } g.drawLine(200,200,500,200); } 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. In this chapter you are learning how to create class methods. The distinction between creating class methods and object methods will become clear in the next chapter. Section 7.4 User - Declared Parameter Methods

Method Calls With & Without Parameters Parameter method example: double result1 = Math.sqrt(100); double result2 = Math.pow(2,5); Non-Parameter method examples: Bug barry = new Bug(); barry.move(); barry.turn(); Overloaded method examples: System.out.println("Hello World"); System.out.println(); // Java0710.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 Java0710 { public static void main(String args[]) { System.out.println("\nJAVA0710.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(); } }

Parameters Terminology Actual Parameters The parameters in the method call. This is the actual information that you are sending to the method. displayParameter(100); Formal Parameters The parameters in the method heading. This is the formal declaration of the parameters. Here their form is determined. public static void displayParameter(int number) // Java0711.java // This program demonstrates that the calling parameter can be: // a constant, like 100; a variable, like value; // an expression with only constants, like 10 + 5;

// an expression with a variable and a constant like value + 5. // A call to a method, which returns a value, like Math.sqrt(100). public class Java0711 { public static void main(String args[]) { System.out.println("\nJAVA0711.JAVA\n"); double value = 100; displayParameter(100); displayParameter(value); displayParameter(100 + 5); displayParameter(value + 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); } } // Java0712.java // This program demonstrates passing two parameters to a method. // The method is called twice. In this case reversing // the sequence of the parameters is not a problem. public class Java0712 { public static void main(String args[]) { System.out.println("\nJAVA0712.JAVA\n"); int width = 100; int height = 50; showArea(width, height);

showArea(height, width); System.out.println(); } } public static void showArea(int w, int h ) { System.out.println(); int area = w * h; System.out.println("The rectangle area is " + area); System.out.println(); } The Football Analogy The Quarterback - The Actual Parameters

showArea(length, width); showArea 100, 50 The Football - A copy of the data The actual parameters pass the data to the formal parameters. The Receiver - Formal Parameters public static void showArea(int L, int W ) // Java0713.java // This program demonstrates that parameter sequence matters. // In this example method will display different // results when the calling parameters are reversed.

public class Java0713 { public static void main(String args[]) { System.out.println("\nJAVA0713.JAVA\n"); int num1 = 100; int num2 = 50; showDifference(num1, num2); showDifference(num2, num1); System.out.println(); } } Parameter sequence is important!

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(); } 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.

// Java0714.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 Java0714 { public static void main(String args[]) { System.out.println("\nJAVA0714.JAVA\n"); showDifference(int num1, int num2); // line 1 System.out.println(); } 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(); } } 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) // Java0715.java // This program demonstrates that multiple parameters may be different data types. public class Java0715 { public static void main(String args[]) { System.out.println("\nJAVA0715.JAVA\n"); // 3 different type parameters method call multiTypeDemo("Hans", 30, 3.575); 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); } } Parameter Rules The parameters in the method call and the method heading must match three ways: 1. They must be the same quantity

2. They must be the same type 3. They must be the same sequence The Track Relay Analogy Race 1 US GB FR NL US GB

FR The second runner from the Netherlands is missing. The number of actual parameters and formal parameters do not match. The Track Relay Analogy Race 2 US GB FR NL US GB NL FR

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. The Track Relay Analogy Race 3 US (John) GB (Charles) US (Greg) GB (William) FR (Gerald) FR (Louis)

NL (Hans) 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. 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 actual parameter identifiers may be the same identifier or a different identifier as the formal parameters. Section 7.5 void Methods & return Methods // Java0716.java This program demonstrates how to use the class with void methods. 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 + " = " + Calc.add(number1,number2); result); } Calc.sub(number1,number2); public static void mul(int n1, int n2) { Calc.mul(number1,number2); int result = n1 * n2;

System.out.println(n1 + " * " + n2 + " = " + Calc.div(number1,number2); result); } System.out.println(); public static void div(int n1, int n2) } { } int result = n1 / n2; System.out.println(n1 + " / " + n2 + " = " + result); } } public class Java0716 { public static void main(String

args[]) { System.out.println( "\nJAVA0716.JAVA\ n"); int number1 = 1000; int number2 = 100; // Java0717.java // This program demonstrates the difference between a // void method and a return method. // There are two differences: // void and return methods are declared differently. // void and return methods are also called differently. public class Java0717 { public static void main(String args[])

{ System.out.println("\nJAVA0717.JAVA\n"); int nbr1 = 1000; int nbr2 = 100; sum1(nbr1,nbr2); System.out.println(nbr1 + " + " + nbr2 + " = " + sum2(nbr1,nbr2)); System.out.println(); } public static void sum1(int n1, int n2) { int sum = n1 + n2; System.out.println(n1 + " + " + n2 + " = " + sum); } } public static int sum2(int n1, int n2)

{ int sum = n1 + n2; return sum; } // Java0718.java // This program reviews different ways to call a return method. public class Java0718 { public static void main(String args[]) { System.out.println("\nJAVA0718.JAVA\n"); System.out.println("Sum: " + sum(200,300)); int sum = sum(200,300); System.out.println("Sum: " + sum); int checking = 200; int savings = 300;

if (sum(checking,savings) <= 0) System.out.println("You are broke!"); else System.out.println("Let's go shopping!"); } } System.out.println(); public static int sum(int n1, int n2) { int sum = n1 + n2; return sum; } // Java0719.java

// This program demonstrates how to create a four-function class // with return methods. public class Java0719 { public static void main(String args[]) { System.out.println("\nJAVA0719n"); 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) { return n1 + n2; } public static int sub(int n1, int n2) { return n1 - n2; } public static int mul(int n1, int n2) { return n1 * n2; } public static int div(int n1, int n2) { return n1 / n2; } } Section 7.6 Making a Utility Library // Java0720.java //

This program demonstrates a user-declared with a variety of methods that can be used in any program. public class Java0720 { public static void main(String args[]) { System.out.println("\nJAVA0711n"); Util.skip(2); System.out.println("This message is left justified"); Util.skip(2); Util.center("This message is centered"); Util.skip(2); Util.rightJustify("This message is right justified"); Util.skip(1);

} } class Util { public static void skip(int n) { for (int k = 1; k <= n; k++) System.out.println(); } public static void center(String str) { int len = str.length(); int tab = (80 - len) / 2; for (int k = 1; k <= tab; k++) System.out.print(" "); System.out.println(str); } public static void rightJustify(String str) { } } int len = str.length(); int tab = 80 - len; for (int k = 1; k <= tab; k++) System.out.print(" "); System.out.println(str); // Java0721.java This program adds the method to the class.

public class Java0721 { public static void main(String args[]) { Util.heading("Leon Schram","Java0721.java", "10-24-06","100 Points"); System.out.println("This message is left justified"); Util.skip(2); Util.center("This message is centered"); Util.skip(2); Util.rightJustify("This message is right justified"); Util.skip(1); }

} public static void center(String str) { int len = str.length(); int tab = (80 - len) / 2; for (int k = 1; k <= tab; k++) System.out.print(" "); System.out.println(str); } public static void rightJustify(String str) { int len = str.length(); int tab = 80 - len; for (int k = 1; k <= tab; k++) System.out.print(" "); System.out.println(str); heading method on }next slide class Util spaces is a { helper method public static void skip(int n) { which is called by for (int k = 1; k <= n; k++) heading System.out.println(); public static String spaces(int n) { String temp = ""; for (int k = 1; k <= n; k++) temp += " "; return temp; } // Java0721.java continued heading method of the Util class public static void heading(String name, String lab, String date, String points) { int nameTab = 28 - name.length(); int labTab = 28 - lab.length(); int dateTab = 28 - date.length(); int pointsTab = 28 - points.length();

Util.skip(2); System.out.println("****************************************************"); System.out.println("****************************************************"); System.out.println("** **"); System.out.println("** Student Name: " + name + spaces(nameTab) + "**"); System.out.println("** **"); System.out.println("** Lab Assignment: " + lab + spaces(labTab) + "**"); System.out.println("** **"); System.out.println("** Date Due: " + date + spaces(dateTab) + "**"); System.out.println("** **");

System.out.println("** Point Version: " + points + spaces(pointsTab) + "**"); System.out.println("** **"); System.out.println("****************************************************"); System.out.println("****************************************************"); Util.skip(2); } } Output for Program Java0721.jav // Java0722.java // This program is identical to Java0721.java with the class // not included in this file.

public class Java0722 { public static void main(String args[]) { Util.heading("Leon Schram", "Lab0722", "10-24-06", "100 Points"); System.out.println("This message is left justified"); Util.skip(2); Util.center("This message is centered"); Util.skip(2); Util.rightJustify("This message is right justified"); Util.skip(1); } } // Util.java // This file is the class. This file can compile by itself, but it cannot execute. // It requires the Java0722.java driver program to test the class.

class Util { public static void skip(int n) { for (int k = 1; k <= n; k++) System.out.println(); } public static void center(String str) { int len = str.length(); int tab = (80 - len) / 2; for (int k = 1; k <= tab; k++) System.out.print(" "); System.out.println(str); } public static void rightJustify(String str) { int len = str.length(); int tab = 80 - len; for (int k = 1; k <= tab; k++) System.out.print(" "); System.out.println(str); } public static String spaces(int n) { String temp = ""; for (int k = 1; k <= n; k++) temp += " "; return temp; } public static void heading(String name, String lab, String date, String points) { int nameTab = 28 - name.length(); int labTab = 28 - lab.length(); int dateTab = 28 - date.length(); int pointsTab = 28 - points.length(); Util.skip(2); System.out.println("****************************************************"); System.out.println("****************************************************"); System.out.println("** **"); System.out.println("** Student Name: " + name + spaces(nameTab) + "**"); System.out.println("** **"); System.out.println("** Lab Assignment: " + lab + spaces(labTab) + "**"); System.out.println("**

**"); System.out.println("** Date Due: " + date + spaces(dateTab) + "**"); System.out.println("** **"); System.out.println("** Point Version: " + points + spaces(pointsTab) + "**"); System.out.println("** **"); System.out.println("****************************************************"); System.out.println("****************************************************"); Util.skip(2); } } 3 Steps of Java Compiling

When the compiler encounters a statement like Util.skip(3) it needs to find the skip method in the Util class. It will look in 3 spaces: 1. It will look for a Util class in the file you are compiling. 2. It will look for a file called Util.class in the folder as the file you are compiling. 3. It will look for a file called Util.java in that same folder, and then compile it into Util.class This is why the file name must match the class name! Section 7.7 The Payroll Case Study The Payroll Case Study

You are about to study eight stages of a case study. This is the first of many case studies that will appear in your textbook. The first program will be very simplistic and each program will make some small change or add something new. // Java0723.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.util.Scanner;import java.text.*; public class Java0723 { public static void main (String args[]) { Scanner keyboard = new Scanner(System.in); String a; double b,c,e,f,g,h,i,j,k; int d; DecimalFormat output = new DecimalFormat("$0.00"); System.out.println("\nPAYROLL

CASE STUDY #1\n"); System.out.print("Enter Name ===>> "); a = keyboard.nextLine(); System.out.print("Enter Hours Worked ===>> "); b = keyboard.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); c = keyboard.nextDouble(); System.out.print ("Enter Dependents ===>> "); d = keyboard.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 = 0.295; break; case 1 : f = 0.249; break; case 2 : f = 0.187; break; case 3 : f = 0.155; break; case 4 : f = 0.126; break; case 5 : f = 0.100; break; default: f = 0.075; } i = g * f; h = g - i; System.out.println("\n\n"); System.out.println("Name: " + a); System.out.println("Hourly rate: " + output.format(c)); System.out.println("Hours worked: " + b);System.out.println("Dependants: " + d); System.out.println("Tax rate: " + output.format(f)); System.out.println("Regular pay: " + output.format(k)); System.out.println("Overtime pay: " + output.format(j)); System.out.println("Gross pay: " + output.format(g)); System.out.println("Deductions: " + output.format(i)); System.out.println("Net pay: " + output.format(h)); System.out.println("\ n\n"); } }

Output for Progr Java0723.java through Java0727.java // Java0724.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

method and there are no program // comments anywhere, nor are the identifiers self-commenting. import java.io.*; import java.text.*; Continued o the next few sl public class Java0724

{ public static void main (String args[]) { Scanner keyboard = new Scanner(System.in); String a; double b,c,e,f,g,h,i,j,k; int d; DecimalFormat output = new DecimalFormat("$0.00"); System.out.println("\nPAYROLL CASE STUDY #2\n"); System.out.print("Enter Name ===>> "); a = keyboard.nextLine(); System.out.print("Enter Hours Worked ===>> "); b = keyboard.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); c = keyboard.nextDouble(); System.out.print("Enter Dependents ===>> "); d = keyboard.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 = 0.295; break; case 1 : f = 0.249; break;

case 2 : f = 0.187; break; case 3 : f = 0.155; break; case 4 : f = 0.126; break; case 5 : f = 0.100; break; default: f = 0.075; } i = g * f; h = g - i; System.out.println("\n\n"); System.out.println("Name: " + a); System.out.println("Hourly rate: " + output.format(c)); System.out.println("Hours worked: " + b); System.out.println("Dependants: " + d); System.out.println("Tax rate: " + output.format(f)); System.out.println("Regular pay: " + output.format(k));

System.out.println("Overtime pay: " + output.format(j)); System.out.println("Gross pay: " + output.format(g)); System.out.println("Deductions: " + output.format(i)); System.out.println("Net pay: " + output.format(h)); System.out.println("\n\n"); } } // Java0725.java // Payroll Case Study #3 // Stage 3 improves program readability by using meaningful identifiers. import java.io.*; import java.text.*; public class Java0725

{ public static void main (String args[]) { Scanner keyboard = new Scanner(System.in); String employeeName; double hoursWorked; double hourlyRate; int numDependants; double overtimeHours; double regularPay; double overtimePay; double taxRate; double grossPay; double taxDeductions; double netPay; Continued o

the next few s DecimalFormat output = new DecimalFormat("$0.00"); System.out.println("\nPAYROLL CASE STUDY #3\n"); System.out.print("Enter Name ===>> "); employeeName = keyboard.nextLine(); System.out.print("Enter Hours Worked ===>> "); hoursWorked = keyboard.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); hourlyRate = keyboard.nextDouble(); System.out.print("Enter Deductions ===>> "); numDependants = keyboard.nextInt(); if (hoursWorked > 40) { overtimeHours = hoursWorked - 40; regularPay = 40 * hourlyRate;

overtimePay = overtimeHours * hourlyRate * 1.5; } else { regularPay = hoursWorked * hourlyRate; overtimePay = 0; } grossPay = regularPay + overtimePay; switch (numDependants) { case 0 : taxRate = 0.295; break; case 1 : taxRate = 0.249; break; case 2 : taxRate = 0.187; break; case 3 : taxRate = 0.155; break; case 4 : taxRate = 0.126; break; case 5 : taxRate = 0.100; break;

default: taxRate = 0.075; } taxDeductions = grossPay * taxRate; 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("Dependants: 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); " + output.format(hourlyRate)); " + hoursWorked); " + numDependants); " + output.format(taxRate)); " + output.format(regularPay)); " + output.format(overtimePay)); " + output.format(grossPay)); " + output.format(taxDeductions)); " + output.format(netPay)); // Java0726.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.io.*; import java.text.*; // provides access to input/output classes // used for text output with class' Continued o the next few sl public class Java0726 { 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 numDependants; // number of dependants 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 dependants, 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 objects // Scanner keyboard = new Scanner(System.in); // keyboard is used for interactive keyboard input DecimalFormat output = new DecimalFormat("$0.00"); // output is used to display values in monetary format //////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// // Program input // System.out.println("\nPAYROLL CASE STUDY #3\n"); System.out.print("Enter Name ===>> "); employeeName = keyboard.nextLine(); System.out.print("Enter Hours Worked ===>> ");

hoursWorked = keyboard.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); hourlyRate = keyboard.nextDouble(); System.out.print("Enter Dependants ===>> "); numDependants = keyboard.nextInt(); ////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // 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; // total pay earned before any deductions switch (numDependants) // compute proper tax rate based on declared // dependants everybody gets 0.075 tax rate if // dependants are greater than 5 { case 0 : taxRate = 0.295; break; case 1 : taxRate = 0.249; break; case 2 : taxRate = 0.187; break; case 3 : taxRate = 0.155; break;

case 4 : taxRate = 0.126; break; case 5 : taxRate = 0.100; break; default: taxRate = 0.075; } taxDeductions = grossPay * taxRate; netPay = grossPay - taxDeductions; // computes 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: " + output.format(hourlyRate));

System.out.println("Hours worked: " + hoursWorked); System.out.println("Dependants: " + numDependants); System.out.println("Tax rate: " + output.format(taxRate)); System.out.println("Regular pay: " + output.format(regularPay)); System.out.println("Overtime pay: " + output.format(overtimePay)); System.out.println("Gross pay: " + output.format(grossPay)); System.out.println("Deductions: " + output.format(taxDeductions)); System.out.println("Net pay: " + output.format(netPay)); System.out.println("\n\n"); ///////////////////////////////////////////////////////////////////////////////////////////// }

} Variable Terminology Local Variables Local variables are defined inside a method. They are only accessible inside that method. public static void computeGrosspay() { double hoursWorked; double hourlyRate; Class Variables Class variables are defined at the beginning of a class -outside of any method. They can be accessed by any method of that class. public class Java0727 { static String employeeName;

// Java0727.java Payroll Case Study #5 // Stage #7 solves the problem of the previous program. The variables are declared in the // class, which makes them available anywhere in the class. The previous program made variables only // available within their respective methods. Only some of the methods are shown on this slide. public class Java0727 { static String employeeName; static double hoursWorked; static double hourlyRate; static int numDependants; static double overtimeHours; static double regularPay; static double overtimePay; static double taxRate; static double grossPay; static double taxDeductions;

static double netPay; public static void main (String args[]) { System.out.println("\nPAYROLL CASE STUDY #5\ n"); enterData(); computeGrosspay(); computeDeductions(); computeNetpay(); printCheck(); } 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 computeNetpay() { netPay = grossPay - taxDeductions; }

// Java0728.java // Payroll Case Study #6 // In Stage 8 the

method is part of the "driving" class, which is the class // responsible for the program execution sequence. The
method now // contains method calls to objects of the class. import java.io.*; import java.text.*; Continued on the next slide. public class Java0728 { 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 { // Only the enterData method is shown static String employeeName; static double hoursWorked; static double hourlyRate; static int numDependants; 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 keyboard = new Scanner(System.in); System.out.print("Enter Name ===>> "); employeeName = keyboard.nextLine(); System.out.print("Enter Hours Worked ===>> "); hoursWorked = keyboard.nextDouble(); System.out.print("Enter Hourly Rate ===>> "); hourlyRate = keyboard.nextDouble(); System.out.print("Enter Dependants ===>> "); numDependants = keyboard.nextInt();

} Variable Terminology 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: Program 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. Section 7.8 Making a GridWorld Library Lab Experiment 0729 Experience has proven that you the speedy students, who like to charge ahead, have trouble

with this experiment. You are doing a GridWorld project differently than you have done previously. If you ignore the instructions and quickly create a project, as you have done previously, then your program will not compile. Have patience and follow the steps carefully. Step 1 Investigate Folder Java0729 NOTE: There is no gridworld.jar file this time. Step 2 Start JCreator

If you do not have the window shown on the left, click View and select File View. Step 3A Click File New Project Step 3B Click Empty Project & Next. Step 3C Click This Button. Step 3D Browse to Java0729 and

click OK. Step 3E DO NOT CLICK FINISH!!!! Instead click Next. Step 4A Click Required Libraries Then click New. Step 4B Type GWCS Library for the Name.

Step 4C Click Add. Click Add Archive. Step 4D Navigate to GridWorld-NoTouchFiles Click gridworld.jar Click Open. Click OK. Step 4E Check this checkbox Click gridworld.jar NowClick Open. ClickClick OK.

Finish Twice. Step 5A Click the Build Project Icon Step 5B If everything was done properly, you will see this in the Build Output window. Step 5C Click the Run Project Icon Section 7.9 Observing the

Bug act Method GridWorld Case Study Files - 01 GridWorld Case Study Files - 02 GridWorld Case Study Files - 03 GridWorld Case Study Files - 04 GridWorld Case Study Files - 05 GridWorld Case Study Files - 06 GridWorld Case Study Files - 07 GridWorld Case Study Files - 08

GridWorld Case Study Files - 09 GridWorld Case Study Files - 10 GridWorld Case Study Files - 11 GridWorld Case Study Files - 12 Observe Bug Method act public void act() { if (canMove()) move(); else turn(); }

Observe Bug Method turn public void turn() { setDirection(getDirection() + Location.HALF_RIGHT); } Section 7.10 Creating New Bug Objects Empty Method Container public void displaySum(int n1, int n2) { }

Method with 1-Line Body public void displaySum(int n1, int n2) { System.out.println(n1 + n2); } Lab Experiment 0730 Mission The mission of this lab experiment is to alter the behavior of the Bug object, such that it will make 90-degree clockwise turns when it cannot move rather than the current 45-degree clockwise turns. Lab Experiment 0730 Step 1

Create a Project for Lab Experiment Java0730 Remember that you need to attach the library that you created in Java0729. It is not necessary to create the library again. That is now done permanently. However, you do need to place a check in front of the library name for each new project Lab Experiment 0730 Step 2A Compile and Execute Java0730 The GridWorld execution will be the same for everybody and for each time that you execute the program. The Bug class is not yet altered to change the behavior of the Bug object.

Click the Run button and observe the behavior of the objects. Lab Experiment 0730 Step 2B You will find that every object acts in the manner that you have observed before. The Rock does nothing. The Actor flips around doing 180-degree turns. The Bug moves one cell and drops a flower, if possible, otherwise turns 45-degrees. The Flower starts out red and slowly turns darker.

Lab Experiment 0730 Step 3A Change the act method as shown below in the Bug.java file. public void act() { if (canMove()) move(); else { turn(); turn(); } } Lab Experiment 0730 Step 3B

Re-compile the project. Execute again and Click Run. Is the behavior as expected? Lab Experiment 0730 CHALLENGE You now need to make several changes to create a new Bug behavior. This time the Bug objects needs to make 90-degree left turns. There are several approaches that will work correctly. Your solution must include a new method, called leftTurn that turns 90-degrees left.

Recently Viewed Presentations

  • Causes Of Frances empire began to collide with

    Causes Of Frances empire began to collide with

    Albany Plan of Union 1754. As the French and Indian War was near there became an urgency for cooperation among the colonies. Plan was to place the colonies under a more centralized government. Drafted by Ben Franklin. Plan failed but...
  • Using PIAAC to Examine Adult Participation in Workforce ...

    Using PIAAC to Examine Adult Participation in Workforce ...

    NUMERACY. Below Average Performance. in the U.S. "the ability to access, use, interpret, and communicate mathematical information and ideas, to engage in and manage mathematical demands of a range of situations in adult life."
  • Secure Electronic Transactions (SET) - unibo.it

    Secure Electronic Transactions (SET) - unibo.it

    SET. SET is an encryption and security specification designed to protect credit card transactions on the Internet.. SET is not itself a payment system. Rather , it is a set of security protocols and formats that enables users to employ...
  • Jacfa Elections

    Jacfa Elections

    Pierre Dussol Richard Masters John Serrati Candis Steenbergen Jeffrey Brown David Desjardins Academic Council Representative (11 members) Academic Council Permanent Substitute (4 members) Angela Vella Violaine Ares Sean Hughes Director of JACFA (the Executive) (5 members) Jeffery Brown Stephen Bryce...
  • Social Skills - earlhaig.ca

    Social Skills - earlhaig.ca

    The reading selections include the following: information paragraph, news report, dialogue, real-life narrative and graphic text (e.g., schedule). They vary in length from a single paragraph to two pages. • Manage your time so that you complete all sections of...
  • Harmadik téma A nemzeti kultúrák elemzése

    Harmadik téma A nemzeti kultúrák elemzése

    Harmadik téma A nemzeti kultúrák elemzése Trompenaars, R. Hall Trompenaars hét kulturális dimenziója univerzalizmus - partikularizmus individualizmus - kollektivizmus neutrális - affektív specifikus - diffúz teljesítmény - egyéb körülmény orientált szekvenciális - szinkronikus belső irányítású - külső irányítású Univerzalizmus -...
  • An Outsider&#x27;s Perspective on European Litigation

    An Outsider's Perspective on European Litigation

    RJR-MacDonald Inc. v. Canada (Attorney General) (1994), 111 D.L.R. (4th) 385, The traditional test for injunctive relief has been that used in RJR-MacDonald Inc. v. Canada (Attorney General) (1994), 111 D.L.R. (4th) 385, and requires a consideration of: Whether there...
  • paediatric acute severe asthma paediatric life threatening asthma

    paediatric acute severe asthma paediatric life threatening asthma

    paediatric acute severe asthma paediatric life threatening asthma evidence consensus experience opinion "what I do" Julie McEniery