Welcome to Lesson 15!
By the end of today's class, you should know...
- How do you properly indent your method code?
- How do you write a proper Javadoc comment for your methods?
- How can methods call other methods?
1. Lesson 14 Practice Exam Questions
Label the components of the following method:
public static double calc_area_circle(int radius) {
double area = 3.14 * radius * radius;
return area;
}
Method Name:
Return type:
Parameter(s):
Write the following method:
-
Name: sumSquare
- It takes two integer parameters
- squares each number (multiplies the number by itself) and then sums the squared numbers
- returns the sum as an integer
Given the starter code below, call the sum of squares method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number1, number2, sumSquares;
System.out.print("Enter the first number: ");
number1 = input.nextInt();
System.out.print("Enter the second number: ");
number2 = input.nextInt();
//call the method here!
System.out.print("The sum of squares is: " + sumSquares);
}
2. Style Requirements for Methods
Proper Indentation
- Consider again our example method
public static int add(int a, int b) {
int sum = a + b;
return sum;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter two numbers to add: ");
int num1 = input.nextInt();
int num2 = input.nextInt();
int total = add(num1, num2);
System.out.println("Sum=" + total);
}
- Note the placement of the curly braces
- There are two common styles of curly brace placement for methods:
- Place the opening brace on the same line as the method heading:
public static int myMethod() {
// statements of the method
}
- Place the opening brace under and lined up with the first letter of the return type:
public static int myMethod()
{
// statements of the method
}
- We can use either style as long as we are consistent
- Also notice the indentation of the statements inside the method
- As before, we always indent 3-4 more spaces after an opening curly brace
- After the closing curly brace, we no longer indent the extra 3-4 spaces
- Indenting makes it easier to see the block of code
- In addition, method names always start with a lower case letter like variables
- We can tell the difference between method and variable name because methods have parenthesis
Group Activity: True or False - The Below Methods Represent Proper Indentation Style
A.
public static int square(int num)
{
return num * num;
}
B.
public static int square(int num) {
return num * num;}
C.
public static int minNum(int num1, int num2) {
if(num1 >= num2) {
return num2;}
else
{return num1;}
}
Javadoc Comments
Commenting Methods
- In addition, good style dictates that you put Javadoc comments before every method:
- Then you use a tool, known as Javadoc, to automatically create program documentation
- For your homework, every method must have a Javadoc comment.
- Comments are for human readers, not compilers
- Your comments should be structured as follows
- Method comments start with
/** and ends with */
- The first line explains the idea of the method, not the implementation
- An
@param entry explains each parameter - one for each parameter in the method
- An
@return entry describes the return value (not required for void methods)
- The following example has two fully commented methods:
/**
* multiplies a number by itself
* @param number the number to square
* @return the squared number
*/
public static double square(double number) {
double result = number * number;
return result;
}
/**
* Formats a date into the month/day/year format
* @param month the current month
* @param day the current day
* @param year the current year
*/
public static void printDate(int month, int day, int year) {
System.out.print(month + "/" + day + "/" + year);
}
public static void main(String[] args) {
//method calls here
}
- Note that if you type /** above a method, Eclipse will help you fill in the rest.
More Information
Activity 15.1: Javadoc Comments (10 pts)
- Copy and paste the below starter code into Eclipse in a class named Comments.java.
- Start the comment and you will see that Eclipse will help you fill in the rest.
- When
you have completed your comments following the Javadoc format described
in the lesson notes above, submit Comments.java to Canvas.
/**
*
* @author
*
*/
public class Comments {
public static boolean isLeapYear(int date) {
if (date % 4 == 0) {
return true;
} else {
return false;
}
}
public static String formatName(String first, char initial, String last) {
return first + " " + initial + ". " + last;
}
public static double areaCircle(double radius) {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
//assume rest of the program here
}
}
3. Methods Calling Methods
- Methods may call other methods
- Within the body of one method, we can call another method call
- Methods can call other methods as often as needed
- We are already doing this when main calls a method
- The following program calls a "helper" method to help calculate the BMI.
- Because
calculating the BMI is a somewhat complicated process, it is helpful to
create a second method to do part of the work for us.
- The heightToSquareInches method handles turning the height from feet and
inches (such as 5'8") into inches squared (such as 68"2).
Example of Methods Calling Methods
|
/**
* Calculates a user's Body Mass Index
* @param feet the user's height in feet
* @param inches the user's height in inches
* @param weight the user's weight in pounds
* @return the Body Mass Index
*/
public static double calculateBMI(int feet, int inches, double weight) {
int inches2 = heightToSquareInches(feet, inches);
double bmi = weight / inches2 * 703;
return bmi;
}
/**
* Converts height in feet and inches to height in inches squared
* @param feet the height in feet
* @param inches the remaining inches
* @return the height in inches squared
*/
public static int heightToSquareInches(int feet, int inches) {
int heightInches = feet * 12 + inches;
int heightInches2 = heightInches * heightInches;
return heightInches2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int height_feet, height_inches;
double weight, bmi;
System.out.print("Please enter your weight in lbs: ");
weight = input.nextDouble();
System.out.print("Please enter your height in feet: ");
height_feet = input.nextInt();
System.out.print("Please enter your remaining height in inches: ");
height_inches = input.nextInt();
bmi = calculateBMI(height_feet, height_inches, weight);
System.out.println("Your BMI is " + bmi);
} |
Activity 15.2: Calculating Your Salary (10 pts)
- Open up Eclipse and create a new Java class called Salary.java.
- Copy and paste the starter code below into the file.
- NOTE: Do not change the starter code! All you need to do is add to it.
import java.util.Scanner;
public class Salary {
//Write your methods here
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int hours;
double hourly_wage;
double weekly_salary = 0;
double monthly_salary = 0;
double yearly_salary = 0;
System.out.println("This program will calculate your weekly, monthly "
+ "and yearly salary!");
System.out.print("Please enter your hourly wage: ");
hourly_wage = input.nextDouble();
System.out.print("Please enter the number of hours you work each week: ");
hours = input.nextInt();
//call methods below
weekly_salary = //method call goes here
monthly_salary = //method call goes here
yearly_salary = //method call goes here
System.out.printf("You make $%.2f per week\n", weekly_salary);
System.out.printf("You make $%.2f per month\n", monthly_salary);
System.out.printf("You make $%.2f per year\n", yearly_salary);
input.close();
}
}
- Now write three methods as follows and place them above main:
weeklySalary():
- Takes an integer argument for the number of hours worked each week
- Takes a double argument for the hourly wage
- Returns a double for the weekly salary
monthlySalary():
- Takes an integer argument for the number of hours worked each week
- Takes a double argument for the hourly wage
- Calls the weeklySalary() method and multiplies the value it returns by 4 to calculate the monthly salary
- Returns a double for the monthly salary
yearlySalary():
- Takes in an integer argument for the number of hours worked each week
- Takes in a double argument for the hourly wage
- Calls the monthlySalary() method and multiplies the value it returns by 12 to calculate the yearly salary
- Returns a double for the yearly salary
- Assume that you work 12 months a year, without vacations
- After you write each method, add a method call and store the result as the appropriate variable.
weekly_salary = //method call goes here
monthly_salary = //method call goes here
yearly_salary = //method call goes here
- Now, run your code and verify that it prints the correct values for each salary type.
- When you are finished, upload your file to Canvas.
Your output should look identical to the following (except user input will vary):
This program will calculate your weekly, monthly, and yearly salary!
Please enter your hourly wage: 15
Please enter the number of hours you work each week: 40
You make $600 per week.
You make $2400 per month.
You make $28800 per year.
Wrap Up
Write a proper Javadoc comment for the below method:
Name: lowerCaseCounter:
- It takes a String parameter
- It returns an int for the total number of lower case letters contained in the String
- Activities 15.1 and 15.2 due Tuesday at 11:59pm
- Assignment 15 due Friday at 11:59pm
~Have a Great Day!~
|
|