Java - Ch. 4 - Methods
A4.2 Simple Method that Multiplies
A4.6 Basic Math with Two Numbers
A4.7 Using a method a few times
4. Methods
4.1 Overview
What is a method:
- Think of a method as a mini-program. Each method has its own name.
- It is created outside the main method, but inside the class brackets.
- A method is a chunk of code which is called by name.
- Used for organizing programs and breaking tasks into more modular pieces.
How methods work:
- Methods are like function notation in algebra. (See Finkel’s lesson on this)
- A method can be called (invoked) at any point in a program simply by utilizing the method's name and handing it variables if that is what is required.
Return types:
- Every method has a return type. This is the type of variable that will be sent back to the program from the method. It can be any of the types of variables that we have studied, but can also be void.
- A void return type means that nothing is returned back to the program. Printing something to the screen is sending something to output, not the program. If you are just printing something to output, the return type should be void.
Example of a simple method:
public static int add(int x, int y) // This is called the method header
{
return x + y; // This method returns the value of x + y
}
- Examining the method header from the example above:
public static int add (int x, int y)
public static - Use this for every method for now.
int - This is the return type. This is the type of variable that the method returns
back to the program. It can be any variable type that we have worked with
add - Method name
int x, int y - This is the parameter list. It is a list of variables, along with their
types that are handed to the method.
How to call a method:
- Using the method in the example above, a full program could look like this:
public static void main(String[] args) // This is the main method that we always use
{
int a = 3;
int b = 100;
int c;
// Call the "add" method and set "c" equal to result. Here, a and b are
// known as the “actual parameters”.
c = add(a, b);
// Print c to the screen
System.out.print(a + " + " + b + " = " + c);
}
// This is the “add” method. Here, x and y are known as the “formal
// parameters”. Parameter a becomes x inside the method and parameter b becomes y.
public static int add(int x, int y)
{
return x + y;
}
OUTPUT: 3 + 100 = 103
(see handout: “I can’t feel my face when I’m with you” for examples of methods)
Chapter 4: Assignments
A4.1 A Very Simple Method
Create a program that takes a boolean, sends it to a method and prints it to the screen directly from the method.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Declare and initialize a boolean variable
// call the printBoolean method
}
public static void printBoolean (boolean x)
{
// prints the output to the screen
}
SAMPLE RUN:
true
A4.2 Simple Method that Multiplies
Create a program that hands three numbers to a method and assigns the product of those numbers to a variable. That variable is then printed to the screen.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Create four variables, three with hard-coded values
int tom = 4;
int sara = 8;
int jack = 10;
int multAnswer;
// Call the method that multiplies the three variables together
// and assigns the result to “multAnswer”
multAnswer = mult3(tom, sara, jack);
// print “multAnswer” to the screen
}
public static int mult3(int pat, int emily, int zora)
{
// create the code that multiplies the parameters together and returns the answer
}
OUTPUT:
4 * 8 * 10 = 320
A4.3 Flip the Boolean
Create a program that takes in a boolean, sends it to a method that returns the opposite of that boolean. The value of the switched boolean will then be printed from the main method.
To switch the value of a boolean variable, you can use the “!” symbol. For example, if the variable w is given a value of true, !w would have a value of false.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Print a line requesting a boolean
// Assign the input to a variable called “origBoolean”
// Call the method and assign the returned value to a new variable like this:
boolean flipped = flipBoolean(origBoolean);
// Print the new variable
}
public static boolean flipBoolean (boolean x)
{
// returns the opposite of the boolean parameter (hint: use !x)
}
SAMPLE RUN #1:
Please give me a boolean (true or false):
true
The opposite of that boolean is false.
SAMPLE RUN #2:
Please give me a boolean (true or false):
false
The opposite of that boolean is true.
A4.4 Square a Number
Write a program that finds the square of a number using a method.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Print a line requesting a number to be squared from the user
// Assign the input to a variable called “num”
// Call the method and hand it the variable. Assign the returned value to a
// new variable called squared like this:
int squared = square(num)
// print the value of squared
}
public static int square(int number)
{
// Returns the value of number squared
}
SAMPLE RUN #1:
What number would you like to square? (integer please)
4
That would be 16.
SAMPLE RUN #2:
What number would you like to square? (integer please)
10
That would be 100.
A4.5 Modulus Calculator
Write a program that takes a dividend and divisor and calculates the modulus. (See sample run below for clarification of dividend and divisors)
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// print a line showing a modulus example
// print a line asking for the dividend
// assign the dividend to a variable
// print a line asking for the divisor
// assign the divisor to a variable
// call the modulus method and hand it two parameters
// the result should be stored in a variable:
int mod = modulus(dividend, divisor)
// print the answer with proper formatting
}
public static int modulus (int divid, int divis)
{
// returns the answer of divid % divis
}
SAMPLE RUN:
Example of modulus: 5 % 2 = 1 where 5 is the dividend and 2 is the divisor.
Please give me the dividend:
18
Please give me the divisor:
4
18 % 4 = 2
A4.6 Basic Math with Two Numbers
Takes two numbers and adds, multiplies, and subtracts them with each operation being done in a separate method.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Print a line asking for a number
// Assign the number to a variable called “num1”
// Print a line asking for a number
// Assign the number to a variable called “num2”
// Say “Thanks!”
// Call the “add” method and hand it num1 and num2. Assign the result to a
// variable.
// Print the result to the screen with proper formatting
// Call the “mult” method and hand it num1 and num2. Assign the result to a
// variable.
// Print the result to the screen with proper formatting
// Call the “sub” method and hand it num1 and num2. Assign the result to a
// variable.
// Print the result to the screen with proper formatting
}
public static int add (int n1, int n2)
{
// return the answer of n1 + n2
}
public static int mult (int n1, int n2)
{
// return the answer of n1 * n2
}
public static int sub (int n1, int n2)
{
// return the answer of n1 - n2
}
SAMPLE RUN:
Please give me a number to do some math on:
7
Please give me a second number:
2
Thanks!
7 + 2 = 9
7 * 2 = 14
7 - 2 = 5
A4.7 Using a method a few times
This program finds the average of a first batch of numbers, a second batch of numbers, a third batch of numbers and then the average of all three batches. It will use the “avg3” method four times.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Create thirteen variables, nine with hard-coded values
double firstBatch1 = 7.0;
double firstBatch2 = 10.0;
double firstBatch3 = 30.0;
double firstBatchAvg; // You could call the method here (answer: 15.6666)
double secondBatch1 = 4.0;
double secondBatch2 = 6.0;
double secondBatch3 = 6.0;
double secondBatchAvg; // You could call the method here (answer: 5.3333)
double thridBatch1 = 150.0;
double thirdBatch2 = 220.0;
double thirdBatch3 = 255.0;
double thirdBatchAvg; // You could call the method here (answer: 208.3333)
double allBatchAvg; // This will hold the average of the other three averages
// print “allBatchAvg” to the screen
}
public static double avg3(double x, double y, double z)
{
// create the code that returns the average of x, y and z.
}
OUTPUT:
The overall average is: 76.44 // If the decimals don’t match exactly, its ok
A4.8 Concatenation method
This program will join a bunch of words together to make one long string which will be stored in the sentence variable.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Create the following variables:
String word1 = “The ”;
String word2 = “first ”;
String word3 = “sentence. ”
String word4 = “Now ”;
String word5 = “the “;
String word6 = “second. “
String sentence;
// Call joinStrings six times to create the entire sentence. The first time, hand it
// sentence and word1, the second time hand it sentence and word2, and so
// on….
}
public static String joinStrings(String sent, String newWord)
{
// create the code that adds “newWord” to the end of “sentence”.
// This is done by concatenating two Strings together.
}
OUTPUT:
The first sentence. Now the second.
A4.9 Report Card Generator
Create a program that asks the user for their name and three test grades. It then returns a report card as shown in the Sample Run.
PROGRAM STRUCTURE:
public static void main(String[] args)
{
// Take in all of the variables with appropriate variable names
// Say “Thank you. Here is your report card:”
// Call both methods below to generate the desired results
}
// The header goes here. The method is called avg, should take in three test grades and
// return the average of the test grades.
{
// Calculate and return the average of the three test grades
}
// The method header goes here. It is called printCard and should display the name,
// each test grade and the average, as displayed in the Sample Run.
{
// Print the relevant information. You can call the avg method when you need it
}
SAMPLE RUN:
Please enter your first name: Paul
Please enter your second name: Rudd
What did you get on your first test? 87
What did you get on your second test? 82
What did you get on your third test? 100
Thank you. Here is your report card:
Rudd, Paul
Test #1: 87
Test #2: 82
Test #3: 100
Average: 90