Colorado State University Logo | CS 163/4: Java Programming (CS 1) Colorado State University Logo | CS 163/4: Java Programming (CS 1)
CS 163/4: Java Programming (CS 1)
Computer Science

Lab 02 - Methods

Introduction

In this lab, you will continue working with variables and output, while familiarizing yourself with how to incorporate methods and objects into your program.

Goals for today:

  • Review input and output using scanners and print statements
  • Practice writing methods from scratch and with stubs

An Overview of Methods

Methods are blocks of code within a program that can be called to complete a task within the program. They exist outside main but within a class. They take parameters in, which are variables that can be used within the method, and can also return a single variable. A program is able to call a method to perform a task.

Imagine if I were to tell you to make a peanut butter and jelly sandwich. My command would be equivalent to the method call. If I gave you bread, peanut butter, and jelly, those would be equivalent to the parameters of a method. And the sandwich you gave back to me would be the return type.

Every method starts with the method signature, which has the following format:

[access modifier] [return type] [method name] ( type parameter1, type parameter2 ) {
	method body
	return statement (if applicable)
}

Access modifiers are usually private or public. For right now, all of our methods will be public, which means that anyone can see them and use them.

Method signatures may also include the keyword static which means that they do not require an instance of the class (an object), to be called. The lack of the keyword static means that the method does require an instance of the class (an object), to be called.

The return type can either be a variable type, like int or char, or void. If it is void, your method does not return anything, and if it is another type, you must make sure to return that type variable within the method body.

For example, a method that calculates a circle’s area would have a method that looked something like this:

1
2
3
4
5
public class Circle{
    public double calculateArea(double radius){
		return 3.14 * radius * radius;
    }
}

To call a method, you can call the method name followed by parentheses that surround any parameters you are passing to the method. If the method is not static, you need to create an object that can call that method by calling the object name followed by a period and the method name and parameters in parentheses.

Testing Your Code

For today’s lab, we will be giving you a method called runTests() that will test your code. Initially, it will be commented out, and as you complete each method, uncomment the associated testing in the runTests() method and run your program. Feel free to add more test cases to this method, as it will not be graded.

Step 1 : scannerPractice()

Review Input and Output

Store a user-inputted hourly wage into the appropriate variable type. The user’s wage may be a decimal number such as 12.0. Use a Scanner and System.in. Do this within the method called scannerPractice() in your program. Anyone should be able to access this method (keyword public), it should not require an instantiation of an object to be called (keyword static), and we will only be printing in this method.

Print the output in proper format, like so: Hourly Wage: $13.15

TIP: We are only printing inside this method, so the keyword void in the method signature tells us not to return anything.

Testing Your Method

Test your method by running the program. Don’t forget to give Zybooks your input in the box! :) With a given input of 12.0 the following will output, shown all in bold:

Hourly Wage: $12.0

Ask yourself … why is it not two zeros?

Step 2 : calculateYearlySalary(double hourlyWage)

Write a method that takes in the user’s hourly wage as a parameter and calculates their yearly salary, based on a working week of 40 hours and a working year of 50 weeks. Return the yearly salary from the method. Anyone should be able to access this method, and it should not require an instantiation of an object to be called.

Hint: What keywords should be included in the method signature?

Testing Your Method

Uncomment the section in the runTests() method labeled Calculate Yearly Salary. Run your program, and check the output.

Step 3 : calculateTax(double salary, int percentage)

Write a method that takes in the user’s annual salary and calculates the taxes owed based on a specific tax bracket, which is given as a percentage (0% -100%) in a parameter. The taxes owed should be returned as a double. We will be calculating the percentage of their income given salary and percentage. For example, if calculateTax(100000, 20) is called, the method should return 20,000.

Hint: Do we want to be working with percentages (out of 100) or decimals? How do we make a percentage a decimal?

1
public static double calculateTax(double salary, int percentage){ }

Testing Your Method

Uncomment the section in the runTests() method labeled Calculate Tax. Run your program, and check the output.

Step 4 : pizzaBudget(double salary)

Write a method that takes in the user’s annual salary and calculates how many pizzas per week the user can buy with that salary. We will assume a pizza costs 12 dollars, and 52 weeks in a year. The method returns an integer.

Think about why we chose to return this type, even if the result from dividing the salary by the price of a pizza does not return a whole number.

1
public static int pizzaBudget(double salary){ }

So you know, to convert from a double to an integer, you have to explicitly “cast” the variable. For example:

1
2
3
4
public static int pieSlices() {
   double pi = 3.14;
   return (int)pi; // returns 3
}

Testing Your Method

Uncomment the section in the runTests() method labeled Pizza Budget. Run your program, and check the output.

Step 5 : calculateSavings(double salary, int currAge, int retirementAge, int percent)

Write a method that takes in the user’s annual salary, current age, desired retirement age, and percent saved each year as parameters. It will calculate how much the user will have saved by the time they retire. The return is a double.

For example, if the user’s current age was 30, their desired retirement age was 60, their salary was $70,000, and their percent saved was 20%, we should be able to call calculateSavings(70,0000, 30, 60, 20), to get a result of $420,000.

Hint: do we want to be working with percentages or decimals?

The method signature is as follows:

1
public static double calculateSavings(double salary, int currAge, int retirementAge, int percentSaved){ }

Hint: Break the calculation up into pieces: the difference between ages to get the years worked, finding the percent as a decimal instead of an int, and multiplying the percentage by the salary then the years worked.

Testing Your Method

Uncomment the section in the runTests() method labeled calculateSavings. Run your program, and check the output.

Computer Science Department

279 Computer Science Building
1100 Centre Avenue
Fort Collins, CO 80523
Phone: (970) 491-5792
Fax: (970) 491-2466

CS 163/4: Java Programming (CS 1)

Computer Programming in Java: Topics include variables, assignment, expressions, operators, booleans, conditionals, characters and strings, control loops, arrays, objects and classes, file input/output, interfaces, recursion, inheritance, and sorting.