Welcome to Lesson 16!
Learning Objectives
By the end of today's class, you should know...
- What is a void method?
- What is the difference between a void and non-void method?
- How do you call a void method (compared to a non-void method)?
- When do you use a void method?
Lesson 15 Practice Exam Questions
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
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; //optional
}
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 = Math.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 16.1: 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 class named DateTime
- Copy and paste the starter code below into your file:
/**
* @author
* CIS 36A, Activity 16.1
*/
import java.util.Scanner;
public class DateTime {
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
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
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
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 (above or below is fine!).
- 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:
More Method Practice
Activity 16.2: More Method Practice (10 pts)
- Copy and paste the starter code into a new file called Methodical.java
- Write the required methods as described by the comments (i.e. you fill in the body of the method).
- Then, run the code when you are finished to see if you wrote the methods correctly.
- Check the test results and make any alterations to your methods as necessary.
- When all of the tests pass, upload your code to Canvas.
/* * @author * CIS 36A, Activity 16.2 */
public class Methodical { /* * Given two int values, returns their sum. * Unless the two values are the same, then return double their sum. * sumDouble(1, 2) → 3 * sumDouble(3, 2) → 5 * sumDouble(2, 2) → 8 */ public static int sumDouble(int a, int b){ return 0; } /* * Given 2 ints, a and b, return true if one of them is 10 * or if their sum is 10. * makes10(9, 10) → true * makes10(9, 9) → false * makes10(1, 9) → true */
public static boolean makes10(int a, int b) { return false; } /* * We have two monkeys, a and b, and the parameters * aSmile and bSmile indicate if each is smiling. * We are in trouble if they are both smiling * or if neither of them is smiling. * Return true if we are in trouble. * monkeyTrouble(true, true) → true * monkeyTrouble(false, false) → true * monkeyTrouble(true, false) → false */
public static boolean monkeyTrouble(boolean aSmile, boolean bSmile) { return false; } /*Return true if the given non-negative number is a multiple of 3 * or a multiple of 5. Use the % "modulus" operator * or35(3) → true * or35(10) → true * or35(8) → false * */
public static boolean or35(int a) { return false; }
/* * Given a String, return a new string where "not " has been added to the front. * However, if theString already begins with "not", return the string unchanged. * notString("candy") → "not candy" * notString("x") → "not x" * notString("not bad") → "not bad" */ public static String notString(String str) { return ""; }
/* * Given a string, return a new string where the first and last chars have been exchanged * frontBack("code") → "eodc" * frontBack("a") → "a" * frontBack("ab") → "ba" */ public static String frontBack(String str) { return ""; } /* * We'll say that a number is "teen" if it is in the range 13..19 inclusive. * Given 3 int values, return true if 1 or more of them is/are teen. * hasTeen(13, 20, 10) → true * hasTeen(20, 19, 10) → true * hasTeen(20, 10, 13) → true */
public static boolean hasTeen(int num1, int num2, int num3) { return false; }
public static void main(String[] args) { int result; boolean answer; String value; System.out.println("***Testing sumDouble***\n"); result = sumDouble(1, 2); System.out.println("Should print 3: " + result); result = sumDouble(3, 2); System.out.println("Should print 5: " + result); result = sumDouble(2, 2); System.out.println("Should print 8: " + result +"\n"); System.out.println("***Testing makes10***\n"); answer = makes10(9, 10); System.out.println("Should be true: " + answer); answer = makes10(9, 9); System.out.println("Should be false: " + answer); answer = makes10(1, 9); System.out.println("Should be true: " + answer + "\n"); System.out.println("***Testing monkeyTrouble***\n"); answer = monkeyTrouble(true, true); System.out.println("Should be true: " + answer); answer = monkeyTrouble(false, false); System.out.println("Should be true: " + answer); answer = monkeyTrouble(true, false); System.out.println("Should be false: " + answer + "\n"); System.out.println("***Testing or35***\n"); answer = or35(3); System.out.println("Should be true: " + answer); answer = or35(10); System.out.println("Should be true: " + answer); answer = or35(8); System.out.println("Should be false: " + answer + "\n"); System.out.println("***Testing notString***\n"); value = notString("candy"); System.out.println("Should be not candy: " + value); value = notString("x"); System.out.println("Should be not x: " + value); value = notString("not bad"); System.out.println("Should be not bad: " + value + "\n"); System.out.println("***Testing frontBack***\n"); value = frontBack("code"); System.out.println("Should be eodc: " + value); value = frontBack("a"); System.out.println("Should be a: " + value); value = frontBack("ab"); System.out.println("Should be ba: " + value + "\n"); System.out.println("***Testing hasTeen***\n"); answer = hasTeen(13, 20, 10); System.out.println("Should be true: " + answer); answer = hasTeen(20, 19, 10); System.out.println("Should be true: " + answer); answer = hasTeen(20, 10, 13) ; System.out.println("Should be true: " + answer); answer = hasTeen(20, 10, 45) ; System.out.println("Should be false: " + answer + "\n"); System.out.println("***End of Tests***"); } }
Wrap Up
Q1: Write a proper Javadoc comment for the below method:Name: displayPrice- takes in one double parameter for a price
- Prints the price to the console with a dollar sign and to two decimal places
- returns nothing
Q2: Write the below method:
- Name: displayPrice
- takes in one double parameter for a price
- Prints the price to the console with a dollar sign and to two decimal places
- returns nothing
Q3: Now call the method using the starter code below:
public static void main(String[] args) { Scanner input = new Scanner(System.in); double number; System.out.print("Enter the price: "); number = input.nextDouble(); System.out.print("The formatted price is: "); //call the method here! }
Upcoming Assignments- Activity 16.1 and 16.2 due Tuesday at 11:59pm
- Assignment 15 due Tuesday at 11:59pm
- Assignment 16 due Friday at 11:59pm
- Quiz 8 due Friday at 11:69pm
|