17
Java@Ch5.Methods 2010.11.05

Java @Ch5.Methods 2010.11.05. Outline Overloading Methods The Scope of Variables The Math Class Floating point Format [Sample code] TestMethodOverloading.java

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

[email protected]

2010.11.05

Outline

• Overloading Methods

• The Scope of Variables

• The Math Class

• Floating point Format

[Sample code] TestMethodOverloading.java 、 AmbiguousOverloading.java

FloatFormat.java

Overloading Methods

定義 :

Method name is the same

but the operation will be different.

解釋 : Overloading 有人將他稱為「多載」,是指

說在「相同類別」中,定義「名稱相同」,但是「引數個數不同」,或是「引數型態不同」的函式,這樣 Java 就可以根據引數的個數、或是引數的型態,呼叫到對應的函式。

程式 :

TestMethodOverloading.java

課本 p.193

max(3,4) max(3.0,5.4)

max(3.0,5.4,10.14)

public static int max(int num1, int num2)

public static double max(double num1, double num2)

public static double max(double num1, double num2, double num3)

程式 :

AmbiguousOverloading.java

課本 p.194

The Scope of Variables

[ 變數的有效範圍 ]

public static void main()

{

int a = 20;

for( int b=0 ; b<10 ; b++ )

{

println(b);

}

println(a);

}

The scope of a The scope of b

課本 5.9 節

The Scope of Variables

[ Java 變數重複宣告的錯誤 ]

public static void main()

{

int a = 20;

for( int a=0 ; a<10 ; a++ )

{

println(a);

}

println(a);

}

The scope of a The scope of a

課本 5.9 節

C program

C 在巢狀 blocks 中可以宣告同名的變數Java 不行

Global( 全域 ) & Local( 區域 ) Variable

• C 有「全域變數」和「區域變數」的概念

• Java 只有「區域變數」的概念• Java 的全域變數比較類似 Class variable

( 定義在 method 裡的變數 , 是一種 local variable)

※ In Java, all variables that are not local

variables are fields of a class.

課本 p.195

Global Variable Sample in C

The Math Class

• Trigonometric

• Exponent

• Rounding

• min, max, abs

• random

課本 5.10 節

The random method

範圍 :

0 <= Math.random() < 1.0

EX:

(int) (Math.random() * 10) 0 to 9

50 + (int) (Math.random() * 50) 50 to 99

練習 :

寫一個 Method , 亂數產生 a~z

課本p.119~120

Floating point Format

程式 ( 補充 ):

FloatFormat.java

練習 :

( 喜八辣 )

1. 電腦與玩家各擲兩顆骰子2. 方法 getRandomNum() 產生 1~6 的

亂數3. 方法 compare(a,b), 比較點數大小