ch5 Methods

5-1 Introduction

5-2 Defining a Method

public class EX01_TestMax {
	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;
	}
}

int z = max(a, b);

p.181 Figure 5.1 A method definition consists of a method header and a method body

5-3 Calling a Method

參考 p.182 程式 Listing 5.1 TestMax.java

p.138 Figure 5.2 when the max method is invoked, the flow of control transfers to it. Once the max method is finished, it returns control back to the caller

p.183 Caution return

public static int sign(int n) {
	if (n > 0)
		return 1;
	else if (n == 0)
		return 0;
	else // else if (n < 0) will compiler error
		return -1;
}

5-3-1 Call Stacks

p.184 Figure 5.3 Call Stacks

5-4 void Method Example

參考 p.184 程式 Listing 5.2 TestVoidMethod.java

參考 p.185 程式 Listing 5.3 TestReturnGradeMethod.java

5-5 Passing Parameters by Values

參考 p.187 程式 Listing 5.4 Increment.java

參考 p.187 程式 Listing 5.5 TestPassByValue.java

5-6 Modularizing Code

參考 p.189 程式 Listing 5.6 GreatestCommonDivisorMethod.java

參考 p.190 程式 Listing 5.7 PrimeNumberMethod.java

5-7 Problem: Converting Decimals to Hexadecimals

參考 p.191 程式 Listing 5.8 Decimal2HexConversion.java

System.out.printf("decimail %1$d = %1$X \n", decimal);

5-8 Overloading Methods

參考 p.193 程式 Listing 5.9 TestMethodOverloading.java

5-9 The Scope of Variables

p.195 Figure 5.5 Variable Scope

p.195 Figure 5.6 A variable can be declared multiple times in nonnested blocks but only once in nested blocks

p.195 Caution Do not declare a variable inside a block and then attempt to use it outside the block

5-10 The Math Class

r = (int) (Math.random() * 10); // 0..9
r = 50 + (int) (Math.random() * 50); // 50..99
r = a + (Math.random() * b); // [a, b)

Math.Random vs. Util.Random

5-11 Case Study: Generating Random Characters

參考 p.199 程式 Listing 5.10 RandomCharacter.java

參考 p.200 程式 Listing 5.11 TestRandomCharacter.java

5-12 Method Abstraction and Stepwise Refinement

p.201 Figure 5.8 Black Box

5-12-1 Top-Down Design

p.202 Figure 5.9 PrintCalendar(readInput, printMonth(printMonthTile, printMonthBody))

5-12-2 Top-Down or Bottom-Up Implementation

5-12-3 Implementation Details

參考 p.205 程式 Listing 5.12 PrintCalendar.java