Welcome to Lesson 18!


Learning Objectives
By the end of today's class, you should know...
  • How do you write a void method?
  • What is the difference between a void and non-void method?
  • How can one method call another method?

Announcements

  • Next quiz on Wednesday - methods, methods, methods!
    • How to write a javadoc comment
    • How to write a void method
    • How to write a non-void method
    • How to call a void method
    • How to call a non-void method
  • Lab 8 for Friday
  • Midterm 2 Results:
    • As: 19 (1 100% score)
    • Bs: 6
    • Cs: 4
    • Ds: 6
    • Fs: 5
    • No Shows: 4
  • If you got a D or F - need to change your approach before the final!
    • Start coming to class
    • Start doing the homework
    • Get immediate help when you are stuck
    • Move to the front row
    • Need to make a drastic change
    • Come talk to me for help and advice regarding your specific situation


Review Activity

What is output by the following program? (Do not run the code -- work it out by hand)


public static int mystery(int param) {
System.out.println("param=" + param);
param = param * 2;
return param;
}

public static void main(String[] args) {
    int num = 2;
System.out.println("At first, num=" + num);
int result = mystery(num);
System.out.println("After calling, num=" + num);
System.out.println("And result=" + result);
}
  1. At first, num=2
    param=2
    After calling, num=4
    And result=4
    
  2. At first, num=2
    param=4
    After calling, num=4
    And result=4
    
  3. At first, num=2
    param=2
    After calling, num=2
    And result=4
    
  4. None of these

Write a javadoc comment for the calcTip Method below

  • calcTip
    • Takes in one double parameter for the price of a meal
    • Calculates 15 percent of the price as the tip
    • returns a double for the tip

Write the following methods:

  • calcTip
    • Takes in one double parameter for the price of a meal
    • Calculates 15 percent of the price as the tip
    • returns a double for the tip
  • calcGPA
    • takes in one double parameter for the grade points and one integer parameter for the number of units.
    • divides the grade points by the units to calculate the GPA
    • returns a double for the GPA
  • minNum
    • Takes in two integer parameters
    • determines which of the two numbers is smaller
    • returns the smaller number

How would you call the above calcTip method inside of main?:


public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);   
    double price, tip;

    System.out.print("Enter the price of the meal: ");
    price = input.nextDouble();

    //call the method here

    System.out.printf("You should pay a tip of: $%.2f\n", tip);
}


Void Methods

  • Previously we looked at methods that returned one value
  • Methods returning a value use a return statement
    return result;
  • A method that returns no value is called a void method
  • In Java, void methods are defined like methods that return a value
  • However, the keyword void replaces the return type
  • For example, what do you notice that is different about the following?
    public static void displayDegrees(double degreeFarenheit) {
        double degreeCelsius = 5.0 / 9 * (degreeFarenheit - 32);
        System.out.println(degreeFarenheit
             + " degrees Fahrenheit is equivalent to "
             + degreeCelsius + " degrees Celsius.");
        return;
    }
    
  • There are only two differences between definitions for void methods and other methods:
    • void return type
    • return statement is optional and does not specify a value if used
  • If no return type is specified, the method returns after executing the last statement
  • Here is an example program using the void method shown above

Example Program With a void Method


public static void displayDegrees(double degreeFarenheit) {
    double degreeCelsius = 5.0 / 9 * (degreeFarenheit - 32);
System.out.printf(degreeFarenheit
    + " degrees Fahrenheit is equivalent to "
+ "%.1f degrees Celsius.\n\n", degreeCelsius);
    return;
}

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
double fTemperature;

 System.out.print("Enter a temperature in Fahrenheit: ");
fTemperature = input.nextDouble();

//Notice method call without assigning result to variable
displayDegrees(fTemperature);
}

When to Write void Methods

  • When we use a non-void method, we are asking a question
  • The method returns a value in response to our question
    double square_root = sqrt(9.0);
    
  • When we use a void method, we are giving the computer a command
    displayDegrees(212);
  • We do not expect or receive an answer


Common Errors With void Methods

  • Note that we cannot call a void method from a System.out.print statement
  • For example, the following causes a compile error:
    System.out.println(displayDegrees(fTemperature)); // NO!
  • The reason is that a void methods does not return a value and System.out.println has nothing to print
  • Similarly, we cannot call a void method in an assignment statement:
    double temp = displayDegrees(fTemperature); // NO!
  • There is nothing to assign to the variable temp

Activity 18.1: Printing Squares (10 pts)

  • Remember our programs that used nested for loops to print out shapes.
  • Let's write a similar program with a method that prints squares of different sizes for our user.
  • Open up Eclipse and create a new Java project called Squares.
  • Then, copy and paste the starter code into your file, save it and run it to make sure everything is working properly.

package squares;

/**
 *
 * @author
 */
import java.util.Scanner;
public class Squares {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int length = 0;

        while (length != -1) {
            System.out.println("I will print squares for you!");
            System.out.print("Please enter the length of one side of the square "
                    + "or -1 to quit: ");
            length = input.nextInt();
            //code to call the method
        }
        System.out.println("Thanks for \"square\" dancing with me!");
    }
   
}

  • Now, write a method that prints squares called printSquares(). Your method should take in an integer argument for the length of one side of the square and should return nothing.
  • Call your method inside the while loop so that it will print out a square given the user input for the length of a side.
  • Run the program again. Does it print out a square?
  • When you are finished, upload your squares.java file to Canvas
  • The output of your program should look identical to the sample output below (except user input will vary).


Activity 18.2: Into the Void (10 pts)

  • Void methods are useful for printing out information in a particular format.
  • Let's consider dates and times.
  • In America, we use the 12 hour clock, but in Europe, the 24 hour clock is used. For example, in America, 8:30 at night is represented as 8:30pm, while in Europe, it is represented as 20:30.
  • In America, we write dates in this format MM-DD-YYYY. In Europe, dates are often written as DD.MM.YYYY
  • Let's write a program that uses void methods to format dates and times.
  • We will print each date and time in both the American and European formats for our user.
  • Open up Eclipse and create a new Java project named DateTime
  • Copy and paste the starter code below into your file:
package datetime;

/**
 *
 * @author
 */
import java.util.Scanner;
public class DateTime {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int year;
        int day;
        int month;
        int hour;
        int minutes;
        String dayEve;
        Scanner input = new Scanner(System.in);

        System.out.println("Welcome! This program will print dates and times "
            + "in both the American and European styles!\n");

        System.out.println("First, let's print a formatted date.\n");
  
        System.out.print("Please enter the current year: ");
        year = input.nextInt();
        System.out.print("Please enter the current month: ");
        month = input.nextInt();
        System.out.print("Please enter the current day: ");
        day = input.nextInt();
        System.out.println();
 
        //call to the formatDateAmerican method here
        //call to the formatDateEuropean method here
  
        System.out.println("\nNow, let's print a formatted time.\n");
  
        System.out.print("Please enter the current hour: ");
        hour = input.nextInt();
        System.out.print("Please enter the current minutes: ");
        minutes = input.nextInt();
        System.out.print("Please enter whether it is \"morning\" or \"evening\": ");
        dayEve = input.next();
        System.out.println();

  
        //call to the formatTimeAmerican method here
        //call to the formatTimeEuropean method here

        System.out.println("\nHave a good day!");
    }
   
}


  • Now, you need to write four methods as follows:
formatDateAmerican
takes as input three integer parameter, one for the year, one for the month and one for the day
prints a formatted version of the date to the console, using the format m/d/yyyy
returns nothing
formatDateEuropean
takes as input three integer parameters, one for the year, one for the month and one for the day
prints a formatted version of the date to the console, using the format d.m.yyyy
returns nothing
formatTimeAmerican
takes as input two integer parameters, one for the hour, one for the minutes, and a string parameter that contains either "morning" or "evening"
prints a formatted version of the time to the console, using the format H:MMam or H:MMpm
returns nothing
formatTimeEuropean
takes as input two integer parameters, one for the hour, one for the minutes, and a string parameter that contains either "morning" or "evening"
prints a formatted version of the time to the console, using the 24 hour clock. Note that there is no am or pm in this format.
returns nothing

  • These methods should be written outside of main.
  • When you are finished writing your methods call them in main in the place indicated by the comments.
  • Upload your dateTime.java file to Canvas.

Your output should look identical the output below when you are finished:





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


Wrap Up
  • With your partner, answer the questions from today's learning objectives

Upcoming Assignments