5.2 Defining a Method



Chapter 5: Methods, part 15.2 Defining a MethodSyntax for defining a method:modifier returnType methodName(parameter list)The modifier will usually be public or private. We will discuss the protected modifier later. If the method does not return a value, its return type is void.5.3 Calling a MethodTo call a method, use the method's name and provide the appropriate number and type of parameters. A method to find the maximum value of two integers:public class TestMax { /** Main method */ public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println("The maximum between " + i + " and " + j + " is " + k); } /** Return the max between two numbers */ public static int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; }}5.4 void Method ExampleWrite a program that gets a numeric test score (0-100) from the user and determines its letter grade using the scale: 90, 80, 70, 60. Note: Both of these programs are in the program files from the textbook.Example (TestVoidMethod.java):Version 1: Write it with a void method that just prints out the grade. public static void main(String[] args) { System.out.print("The grade is "); printGrade(78.5); System.out.print("The grade is "); printGrade(59.5); } public static void printGrade(double score) { if (score >= 90.0) { System.out.println('A'); } else if (score >= 80.0) { System.out.println('B'); } else if (score >= 70.0) { System.out.println('C'); } else if (score >= 60.0) { System.out.println('D'); } else { System.out.println('F'); } }Modify the above program to accept input from the user (scores) repeatedly until the user enters a negative number. Use a while(true) loop.Example (TestReturnGradeMethod.java)Version 2: Write it with a char method that returns the grade. public static void main(String[] args) { System.out.printf("The grade is %s.", getGrade(78.5)); System.out.printf("The grade is %s.", getGrade(59.5)); } public static char getGrade(double score) { if (score >= 90.0) return 'A'; else if (score >= 80.0) return 'B'; else if (score >= 70.0) return 'C'; else if (score >= 60.0) return 'D'; else return 'F'; }5.5 Passing Parameters by ValueParameters in Java area always passed by value. Parameter passage by value: A parameter that is passed by value has the argument's value copied into the formal parameter's memory location. All operations are performed on the copy, and the original argument remains unchanged. Example (Increment.java):public static void main(String[] args) { int x = 1; System.out.printf("Before the call, x is %d.\n", x); increment(x); System.out.printf("After the call, x is %d.\n", x);}public static void increment(int n) { n++; System.out.printf("\tn inside the method is %d.\n", n);}There is no pass by reference option in Java like there is in C# and some other languages! This means that it is impossible to write a swap method like this:Example (TestPassByValue.java)public static void main(String[] args) { // Declare and initialize variables int num1 = 1; int num2 = 2; System.out.printf("BEFORE calling swap, num1 is %d " + " and num2 is %d.\n", num1, num2); // Invoke the swap method to attempt to swap two variables swap(num1, num2); System.out.printf("AFTER calling swap, num1 is %d " + " and num2 is %d.\n", num1, num2);}/** Swap two variables */public static void swap(int n1, int n2) { System.out.println("\tInside the swap method"); System.out.printf("\t\tBefore swapping n1 is %d, n2 is %d.\n", n1, n2); // Swap n1 with n2 int temp = n1; n1 = n2; n2 = temp; System.out.printf("\t\tAfter swapping n1 is %d, n2 is %d.\n", n1, n2);}5.6 Modularizing CodeA big advantage of methods is that they allow the programmer to divide his code into modules. Modules should be focused and relatively short. The name of the module (method) should reflect what it does. 5.7 Problem: Converting Decimals to HexadecimalSample problem: Modify Listing 5.8 (Decimal2HexConversion.java, below) to convert from decimal to ANY other base up to 16. The user will have to enter a second value: the base to convert to.Example (Decimal2HexConverstion.java) public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); // Prompt the user to enter a decimal integer System.out.print("Enter a decimal number: "); int decimal = input.nextInt(); System.out.println("The hex number for decimal " + decimal + " is " + decimalToHex(decimal)); } /** Convert a decimal to a hex as a string */ public static String decimalToHex(int decimal) { String hex = ""; while (decimal != 0) { int hexValue = decimal % 16; hex = toHexChar(hexValue) + hex; decimal = decimal / 16; } return hex; } /** Convert an integer to a single hex digit in a character */ public static char toHexChar(int hexValue) { if (hexValue <= 9 && hexValue >= 0) return (char)(hexValue + '0'); else // hexValue <= 15 && hexValue >= 10 return (char)(hexValue - 10 + 'A'); }5.8 Overloading MethodsIn most modern programming languages, it is legal to have multiple methods with the same name. The way the compiler (and the programmer) distinguishes one from another is by looking at the argument list. If the names are the same, the argument lists must be different. Look at the TestMethodOverloading.java program (listing 5.9). See what happens when the version of max that accepts two int arguments and returns an int result is commented out! The program will still compile and it will call the method with the double arguments and double result.public static void main(String[] args) { // Invoke the max method with int parameters System.out.printf("The maximum between 3 and 4 is %d.\n", max(3, 4)); // Invoke the max method with the double parameters System.out.printf("The maximum between 3.0 and 5.4 is %f.\n", max(3.0, 5.4)); // Invoke the max method with three double parameters System.out.printf("The maximum between 3.0, 5.4, and 10.14 is %f.\n", max(3.0, 5.4, 10.14));}/** Return the max between two int values */public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2;}/** Find the max between two double values */public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2;}/** Return the max among three double values */public static double max(double num1, double num2, double num3) { return max(max(num1, num2), num3);}Now uncomment the int version of max and comment out the double version of max. The program will not compile because you cannot pass a double to a method that is expecting an int.5.9 The Scope of VariablesThe scope of a variable is the area of the program where it can be referenced. Scope is generally local or module-level. Module-level variablesModule-level variables are declared outside of any method (but inside of the class) and must have the modifier static before the type. When we write our own classes later, this will not be true, but for now it is. Module-level variables may be declared at any place in the module and are available anywhere in the module.Local variablesLocal variables are declared inside of a method (parameters are local, too!) and are available only in the method in which they are declared. NOTE: It is legal in Java to declare a local variable that has the same name as a module-level variable (it is not legal in C#), but you need to be aware that you are blocking access to the outer variable! Java gives you a warning; C# gives you a compile error.for-loop variablesA special case of "local" variables occurs when a variable is declared in a for loop:for (int i=0; i<10; i++) Console.out.println(i);The scope of the variable i in this case is just the body of the for loop. It is also possible to declare a variable within the body of a for loop. Such a variable's scope is from the line on which it is declared through the end of the loop. It is not visible above its declaration!5.10 The Math ClassThe Math ClassYou can use the following methods (functions) from the Math class (note the capital "M"):Math.min(x, y)Math.max(x, y)Math.sqrt(x)Math.pow(base, power)Math.abs(x)Math.random() //returns a number >= 0 and < 1.The Math class also has many other math functions, but we will probably not use them in this class.5.11 Case Study: Generating Random Numbers The following is not from Liang, but from provides the Math.random() method as well as the java.util.Random class. The methods of the Random class often produce random numbers in a more convenient form, but requires creating an object, which sometimes is inconvenient. In constrast, the Math.random() method produces a double value which must sometimes be translated and cast into the form you need it. It's a tradeoff between the globalness of Math.random and the more directly useful numbers from the Random class.java.util.Random classTo use the Random class create an object of this class (giving a seed to the constructor if you wish), then call one of the methods below to get a new random number. You must use one of the following import statements: import java.util.Random; // Only the Random class import java.util.*; // All classes in the java.util packageRandom constructors Random r = new Random(); // Default seed comes from system time. Random r = new Random(long seed); // For reproducible testingRandom methodsThe most common methods are those which return a random number. These methods return a uniform distribution of values, except?nextGaussian(). In these examples, r is a Random object.Return typeCallDescriptionint i =r.nextInt(int n)Returns random int >= 0 and < nint i =r.nextInt()Returns random int (full range)long l =r.nextLong()Returns random long (full range)float f =r.nextFloat()Returns random float >= 0.0 and < 1.0double d =r.nextDouble()Returns random double >=0.0 and < 1.0boolean b =r.nextBoolean()Returns random double (true or false)double d =xrnextGaussian()Returns random number with mean 0.0 and standard deviation 1.0Using the Random class makes it much easier to generate random integers (e.g. to simulate a deck of cards, the roll of a dice, random colors, etc.). To generate random rolls of a single die:public static void main(String[] args) { // Default seed comes from system time. Random r = new Random(); int[] totals = new int[13]; for (int i=0; i<13; i++) totals[i] = 0; for (int i=1; i<=10000; i++) { int die1, die2, sum; die1 = r.nextInt(6) + 1; die2 = r.nextInt(6) + 1; sum = die1 + die2; totals[sum]++; System.out.printf ("You rolled %d and %d = %d.\n", die1, die2, sum); } for (int i=2; i<=12; i++) { System.out.printf("%2d: %5d ", i, totals[i]); System.out.printf( "%3f \n", (totals[i] / 10000.0)); }}5.12 Method Abstraction and Stepwise RefinementProblem: Print a calendar when given a year and month. See PowerPoint for chapter 5, starting at slide #68. This demonstrates how you might go about designing a solution to this problem. This is a cool program. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download