CISC 1115
Introduction to Programming Using Java
Methods


Reading from the Text

Chapter 4

Methods

Overview

We thus see there are the following components to using a method:

Motivations for Methods

Elimination of Duplicate/Redundant Code

Imagine the code to calculate a letter grade from a numerical grade. This may crop up several times in a student-grading system: for term projects, final exams, quizzes, etc. Rather than repeating the set of conditionals each time, we move it into a method and call it from any location where that logic is used.

Relocation of Distracting Code

Suppose we wanted to print out the output of our grading program in some fancy manner with borders and blank lines, etc. Rather than having all that appear in the middle of our grade calculation logic, we again move it into a method and call it from the location at which it was originally meant to appear

Isolation of Complex, or Esoteric Code

There are various mathematical techniques for calculating square roots, many of them quite sophisticated. Rather than placing these into your code, they are isolated into methods that can be simply called

Assigning a Name to a Task

This is the underlying notion behind methods — it is a means of organizing code into manageable-sized tasks with well-defined, descriptive name.

More Examples of Methods

P04.1 Rounder

Write a program that prompts the user for a double and uses the round method of the Math class to print the integer resulting from rounding the double.

import java.util.*;
import java.io.*;

public class Rounder {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(System.in);

                System.out.print("Enter a double: ");
                double d = scanner.nextDouble();

                System.out.println(d + " rounds to " + Math.round(d));
        }
}
Interactive Session

Here is a sample execution of the program.
User input is in bold.

Enter a double: 23.1
23.1 rounds to 23

P04.2 Pythagoras

Write a program that finds prompts the user for the side of a square and prints the length of the diagonal.

import java.util.*;

public class Pythagoras {
        public static void main(String [] args) throws Exception {
                Scanner scanner = new Scanner(System.in);

                System.out.print("Enter the (integer) length of the side of the square: ");
                int side = scanner.nextInt();

                double diagonal = Math.sqrt(2) * side;

                System.out.println("The length of the diagonal of a square with a side of length " + side + " is " + diagonal);
        }
}
Interactive Session

Here is a sample execution of the program.
User input is in bold.
Enter the (integer) length of the side of the square: 1
The length of the diagonal of a square with a side of length 1 is 1.4142135623730951

Methods from other Classes

Writing Your own Methods — Anatomy of a Method I

P04.3 HelloWorld

Redo HelloWorld using a method for the display of Hello world

Code

class HelloWorld { public static void main(String [] args) { displayHelloWorld(); } public static void displayHelloWorld() { System.out.println("Hello world"); } }

Notes

At the very least, a method definition consists of

Stdout
Hello world
P04.4 AsciiA

Write a program containing a method, printA, that prints an 'ASCII art' letter A:

      A      
     A A     
    A   A    
   AAAAAAA   
  A       A  
 A         A 
A           A
Code
public class AsciiA {
   public static void main(String [] args) {
      printA();
   }
      
   public static void printA() {
      System.out.println("      A      ");
      System.out.println("     A A     ");
      System.out.println("    A   A    ");
      System.out.println("   AAAAAAA   ");
      System.out.println("  A       A  ");
      System.out.println(" A         A ");
      System.out.println("A           A");
   }
}
Stdout

A A A A A AAAAAAA A A A A A A

Lifecycle of a Method

Multiple Methods; Method Composition

P04.5 Box

Write a program that prints the following figure:

!!!!!
*****
*****
*****
*****
*****
!!!!!
The program should contain the following methods:
Code

public class Box { public static void main(String [] args) { printBox(); } public static void printBox() { printBorder(); printFiveLinesOfStars(); printBorder(); } public static void printBorder() { System.out.println("!!!!!"); } public static void printFiveLinesOfStars() { for (int i = 1; i <= 5; i = i + 1) printStars(); } public static void printStars() { System.out.println("*****"); } }

Notes

Stdout

!!!!! ***** ***** ***** ***** ***** !!!!!

Parameters and Arguments — Anatomy of a Method II

We will often need to send information to a method. Methods can accept arguments that are assigned to parameters.
P04.6 FormLetter

Write a program containing a method printFormLetter. printFormLetter accepts two String arguments, representing a first and last name, and uses it to produce a 'personalized' form letter. Have main print out two copies of the form letter to two different people.

Code

public class FormLetter { public static void main(String [] args) { printFormLetter("Mr.", "Gerald", "Weiss"); System.out.println(); System.out.println(); printFormLetter("Professor", "David", "Arnow"); } public static void printFormLetter(String salutation, String first, String last) { System.out.println("Dear " + salutation + " " + last + ","); System.out.println(); System.out.println(" Hello " + first + ", we would like to inform you of our new "); System.out.println("chain of coffee houses in your area, geared to people like you. "); System.out.println(first + ", for a limited time, you can receive your own "); System.out.println("membership card, entitling you to 10% off your first 5 purchases, as well as a "); System.out.println("host of special offers. So hurry up, " + first + " and reply today!"); } }

Notes

Stdout

Dear Mr. Weiss, Hello Gerald, we would like to inform you of our new chain of coffee houses in your area, geared to people like you. Gerald, for a limited time, you can receive your own membership card, entitling you to 10% off your first 5 purchases, as well as a host of special offers. So hurry up, Gerald and reply today! Dear Professor Arnow, Hello David, we would like to inform you of our new chain of coffee houses in your area, geared to people like you. David, for a limited time, you can receive your own membership card, entitling you to 10% off your first 5 purchases, as well as a host of special offers. So hurry up, David and reply today!

'Value'-Returning Methods — Anatomy of a Method III

Methods often calculate results which must be passed back to the caller. A method can have a return value
P04.7 Grader

Rewrite the grading program, adding a first and last name, and using the following methods:

Code

import java.util.*; public class Grader { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); System.out.println("Number of students to process: "); int numStudents = scanner.nextInt(); for (int i = 1; i <= numStudents; i = i + 1) processOneStudent(scanner); } public static void processOneStudent(Scanner scanner) { System.out.print("Last name: "); String lastName = scanner.next(); System.out.print("First name: "); String firstName = scanner.next(); System.out.print("Midterm: "); int midterm = scanner.nextInt(); System.out.print("Final: "); int finalExam = scanner.nextInt(); double average = calcAverage(midterm, finalExam); char grade = calcGrade(average); System.out.println("average: " + average + " grade: " + grade); } public static double calcAverage(int midterm, int finalExam) { return (midterm + finalExam) / 2.0; } public static char calcGrade(double average) { char grade; if (average >= 90) grade = 'A'; else if (average >= 80) grade = 'B'; else if (average >= 70) grade = 'C'; else if (average >= 60) grade = 'D'; else grade = 'F'; return grade; } }

Notes
Stdin

2 Weiss Gerald 80 95 Arnow David 65 75

Stdout

Last name: First name: Midterm: Final: average: 87.5 grade: B Last name: First name: Midterm: Final: average: 70.0 grade: C

Interactive Session

Here is a sample execution of the program.
User input is in bold.

2
Last name: Weiss
First name: Gerald
Midterm: 80
Final: 95
average: 87.5 grade: B
Last name: Arnow
First name: David
Midterm: 65
Final: 75
average: 70.0 grade: C

An Introduction to Some Advanced Concepts

p04.8 ASCIIArt

Write a method printASCIIArt(String s) that accepts a String argument and prints it as ASCII art

Code

import java.util.*; public class AsciiArt { public static void main(String [] args) { // main is acting as a test driver, providing the ability to test the various letters Scanner scanner = new Scanner(System.in); System.out.print("string? "); String s = scanner.next(); printASCIIArt(s); } public static void printASCIIArt(String s) { for (int i = 0; i < s.length(); i = i + 1) printASCIIChar(s.charAt(i)); } public static void printASCIIChar(char c) { switch (c) { case 'A': printASCIIA(); break; case 'B': printASCIIB(); break; case 'C': printASCIIC(); break; case 'D': printASCIID(); break; … case 'Y': printASCIIY(); break; case 'Z': printASCIIZ(); break; case ' ': printASCIIBlank(); break; default: printUnknown(); break; } } … public static void printASCIIA() { System.out.println(" AAA "); System.out.println(" A A "); System.out.println(" A A "); System.out.println(" AAAAAAA "); System.out.println(" A A "); System.out.println(" A A "); System.out.println(" A A "); } public static void printASCIIB() { System.out.println(" BBBBBB "); System.out.println(" B B "); System.out.println(" B B "); System.out.println(" BBBBBB "); System.out.println(" B B "); System.out.println(" B B "); System.out.println(" BBBBBB "); } … public static void printASCIID() { // Test stub System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" D "); System.out.println(" "); System.out.println(" "); System.out.println(" "); } public static void printASCIIE() { System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" E "); System.out.println(" "); System.out.println(" "); System.out.println(" "); } public static void printASCIIF() {System.out.println("F goes here");} // Even shorter test stub public static void printASCIIG() {System.out.println("G goes here");} // Even shorter test stub … public static void printASCIIY() {System.out.println("Y goes here");} // Even shorter test stub public static void printASCIIZ() {System.out.println("Z goes here");} // Even shorter test stub public static void printASCIIBlank() { System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" "); } public static void printUnknown() { System.out.println(" ????? "); System.out.println(" ? ? "); System.out.println(" ? "); System.out.println(" ? "); System.out.println(" ? "); System.out.println(" "); System.out.println(" ? "); } }

Notes
Stdin

BYE!

Stdout

string? BBBBBB B B B B BBBBBB B B B B BBBBBB Y goes here E ????? ? ? ? ? ? ?

Interactive Session
string? BYE!
BBBBBB B B B B BBBBBB B B B B BBBBBB Y goes here E ????? ? ? ? ? ? ?

A Program With Potential

P04.8 Payroll

Write a program that reads in an employee's last name, first name (strings), hours worked, and hourly rate (integers), calculates the gross wages, federal tax, state tax, and net earnings, and prints the results. Federal and state tax both use the same tax table:

Amount % tax
Up to and including $200 0%
$201 up to and including $400 10%
$401 and up 15%

Federal tax is calculated first and deducted from the gross earning; the remainder is then subject to state tax

Code

import java.util.*; public class Payroll { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); System.out.print("last name: "); String lastName = scanner.next(); System.out.print("first name: "); String firstName = scanner.next(); System.out.print("rate: "); int rate = scanner.nextInt(); System.out.print("hours: "); int hours = scanner.nextInt(); int gross = calculateGross(hours, rate); int federalTax = calcTax(gross); int net = gross - federalTax; int stateTax = calcTax(gross); // What's the bug? net = net - stateTax; printReport(lastName, firstName, hours, rate, gross, federalTax, stateTax, net); } public static int calculateGross(int hours, int rate) {return hours * rate;} public static int calcTax(int amount) { if (amount <= 200) return 0; else if (amount <= 400) return (int)(amount * .10); else return (int)(amount * .15); } public static void printReport(String lastName, String firstName, int hours, int rate, int gross, int federalTax, int stateTax, int net) { System.out.println(); System.out.println(); System.out.println("*** Payroll Report for " + lastName + ", " + firstName + " ***"); System.out.println(); System.out.println(hours + " hours worked @ $" + rate + " / hr"); System.out.println(); System.out.println("Gross wages: $" + gross); System.out.println(); System.out.println("--- Witholdings ---"); System.out.println("Federal tax: $" + federalTax); System.out.println("State tax : $" + stateTax); System.out.println(); System.out.println("Net earnings: $" + net); } }

Stdin

Weiss Gerald 20 32

Stdout

last name: first name: rate: hours: *** Payroll Report for Weiss, Gerald *** 32 hours worked @ $20 / hr Gross wages: $640 --- Witholdings --- Federal tax: $96 State tax : $96 Net earnings: $448

Interactive Session

Here is a sample execution of the program.
User input is in bold.
last name: Weiss
first name: Gerald
rate: 20
hours: 32


*** Payroll Report for Weiss, Gerald ***

32 hours worked @ $20 / hr

Gross wages: $640

--- Witholdings ---
Federal tax: $96
State tax : $96

Net earnings: $448

Future Work

Files used in Lecture 4

Lab for Lecture 4