Lab #4 - Writing and Executing Methods Contained in the Same Program
Write an application that contains two static methods: main and sumSquares. The sumSquares method takes five integer arguments and returns one integer value. The method first squares each of the five values passed to it. It then adds together each of the squared results. The sum of the squared values if then returned.
Objectives:
Upon completion of this lab the student will be able to:
Describe and understand the structure and format of methods used in the Java programming language.
Write a method in a Java application program.
Invoke or call (cause the method to execute) a method.
Understand what arguments (synonymous with parameters) are as identified in a method header.
Pass values to a method when calling the method.
Return a value from a method.
Step by step instructions:
1. Write a Java application called ExMethods. In this program called ExMethods, write a method called main which enters five values for five integer variables. You can use a Scanner object to input each of the five values (one value for each of the five variables). Use a println statement to prompt the user to enter each of the five values.
2. After entering values for these five variables (still in method main) call a method named sumSquares, passing it the five integer values which were entered.
3. Write the method sumSquares. This method should have five integer values for arguments. This method should find the sum of the squares of the five integer values and return this sum. For example, if the five values passed to the method are 4, 5, 2, 1 and 0, then the sumSquares method would first calculate the sum of the squares equal to 4 * 4 + 5 * 5 + 2 * 2 + 1 * 1 + 0 * 0. The method sumSquares would then return the value of this calculated sum.
4. In method main the value returned by the sumSquares method should be displayed using the println statement.
import java.util.Scanner; public class ExMethods { public static void main(String []args) { Scanner keyboard = new Scanner(System.in); int i = 0; int num1 = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = 0; int sum; System.out.println("Enter a number:"); num1 = keyboard.nextInt(); System.out.println("Please enter a second number:"); num2 = keyboard.nextInt(); System.out.println("Please enter a third number:"); num3 = keyboard.nextInt(); System.out.println("Please enter a forth number:"); num4 = keyboard.nextInt(); System.out.println("Please enter a fifth number:"); num5 = keyboard.nextInt(); sum = sumOfSquares(num1,num2,num3,num4,num5); System.out.println("The sum of squares equals:" + sum); } public static int sumOfSquares( int num ) { return (int) Math.pow(num * (num + 1) / 2, 2); } } System.out.println("The sum of the squares is: " + sum); } }