Java系列概論 Java System Concepts

Download Report

Transcript Java系列概論 Java System Concepts

Java系列概論
Java System Concepts
基礎入門程式
Basic Programming
• 自1990年昇陽開始研發Java以來,至今Java儼然已成為
最具網路潛力的程式語言。目前大多數之網路線上遊戲、
網路銀行都是以Java撰寫而成。
•
• 筆者感慨到,我們不知道自己以後會有多大的成就,也
許是大企業家、大科學家、或是政治家,但有一點可以
確定的,只要從事電腦工作,我們就一定會應用到Java,
統計目前市場上網路應用之產品,70%以上是由Java撰
寫,聽起來似有些誇張,但事實就是如此。
•
• 最近美國市場最熱門的I-phone被批評有瑕疵,原因是
Java不是MacOS系統之強項,由此也可看出,Java在網
路系列應用之重要性。
本書特色
(1) 輕鬆入門:本書以初學入門觀點切入,配合範例輕鬆
解說、輕鬆學習。
(2) 熟練實作:學習重點搭配範例實作,再以SCJP認證模
擬試題重複演練,完全剖析Java。
(3) 問題導向:幫助讀者提出問題,解決問題,編輯問題
640則(其中223則範例、146則習題、271則認證模擬
試題)。
(4) 原文接軌:編輯中英文索引537個,涵蓋所有Java之
中英文專有名詞,足夠讓讀者儲備閱讀原文書籍的能
力。
第一章
導讀(Introduction)
1-1 簡介
• Java是由C++ 淵源發展而成,1990年昇陽(Sun
Microsystems) 為發展資訊應用(Information Appliance) 成
立 “綠色(Green)” 小組,主要研發消費性家電之控制語
言,小組成員James Gosling因研究室窗外的橡樹將軟體
最初取名為“Oak”,因Oak已被其他公司採用為商標,改
以悠閒且不離手的咖啡感覺將軟體定名為“Java”。
•
• 1995年,昇陽正式公開 “Java Applet” 上市,主要用於網
頁與使用者間互動的小程式,爾後再經過努力開發,至
今Java儼然已成為最具網路潛力的程式語言。目前大多
數之網路線上遊戲、網路銀行都是以Java撰寫而成。
1-2 Java系統架構
Java的系統架構可類分為3組區塊:
(1) 使用者程式區塊(User’s Program Component),
(2) 應用程式介面區塊(API Application
Programming Interface Component),
(3) 虛擬機器區塊(Virtual Machine Component)。
圖1-2-2
圖1-2-3
1-3 Java執行環境
(Java Development Environment)
1-3 Java執行環境
(Java Development Environment)
1-4 Java特性
1、精緻簡單(Simple):不需大容量儲存記憶體、或龐大套裝應用軟體,Java類別
程式(xxx.class) 可直接搭配系統內建方法程序(Methods) 執行有關功能。
•
2、物件導向(Object Oriented):物件關係是最接近我們人類的邏輯思維,以物件
為問題標的,將容易模擬我們解決問題的方法。
•
3、跨平台(Cross Platforms):如圖1-2-3,Java可依附各種作業系統平台執行,不
受執行環境之限制。
•
4、編譯(Compiler)/直譯(Interpreter):如圖1-3-1,Java原始程式(xxx.java) 經過編
譯器產生機器碼(xxx.class),再搭配Java API程式以直譯方式執行。因有編譯過
程,故一次執行,到處使用;因是直譯執行,故迅速便捷。
•
5、安全(Secure):提供周嚴保護措施,且無指標(Pointer) 應用,充分保護記憶體
資料之安全。
•
6、網路功能(Network Functions):不必架設網站,Java程式碼本身就有網路功能,
直接執行網路資料傳輸。
1-5 Java版本
1 企業版J2EE (Java2 Enterprise Edition) 提供企 業伺
服端應用;
2 標準版J2SE (Java2 Standard Edition) 提供一般程式
開發應用;
3 微電腦版J2ME (Java2 Micro Edition) 提供微電腦應
用,如手機、PDA、資訊家電等之開發。
1-6 Java認證
1 程式設計師認證SCJP(Sun Certified Programmer for Java2 Platform):
認證對象為Java程式設計師(Programmer)。
2 研發工程師認證SCJD(Sun Certified Developer for Java2 Platform):
認證對象為Java研發工程師(Developer),必須先取得SCJP認證資
格者,才可參加本項認證測驗。
3 網路研發工程師認證SCWD(Sun Certified Web Component
Developer for Java2 Enterprise Edition J2EE Platform):認證對象為
Java Web網路研發工程師(Web Developer),必須先取得SCJP認證
資格者,才可參加本項認證測驗。
4 企業結構工程師認證SCAJ(Sun Certified Enterprise Architect for
Java2 Technology):為Java之最高級認證,認證對象為Java結構
工程師,不須先取得其他認證資格,有PartⅠ、PartⅡ、PartⅢ
三項測驗,必須三項全部通過才可取得證照。
第三章
Java程式基礎架構與元素
3-1 簡介
•
撰寫Java程式,也與撰寫其他語言程式一樣,有其自己的
架構元素與格式,本章將以初學入門的觀點,先認識一個
簡易Java程式的組成架構與元素。
•
• 對初學者來言,Java程式之基礎架構有程式名稱、執行區
塊、執行起始點、敘述、與符號;Java程式之基礎組成元
素有 “類別程序(Class Procedures)”,亦即 “物件(Objects)”。
3-2 Java基礎架構
•
•
•
•
•
1、程式名稱(Names)
2、執行區塊(Blocks)
3、執行起始點(Execution Start)
4、敘述(Statements)
5、符號(Signs)。
3-3 Java基礎元素
• 在Java環境中,一個類別程序(Class Procedure) 就是一個物
件。
• Java檔案包含多個類別程序,這些類別程序組成的物件,
亦就是Java檔案的基礎元素,也是我們學習Java的起始點。
類別程序
•
•
•
•
•
1 class MyfirstJava{
2
public static void main(String[ ] args){
3
System.out.println("My first Java program");
4
}
5 }
3-4 關鍵字(Key words)
• Java系統有一些關鍵字(Key words),讀者在學習之
初應先作認識。這些字有特殊之意義,於編輯程
式時除了用在其允許的位置,不得用於其他地方。
同時關鍵字也是SCJP的常考題。常用關鍵字之數
量並不多,各字之有關意義與用法,將於爾後詳
細介紹。
第四章
變數宣告(Variables)
4-1 簡介
• 於Java程式中,所有被使用的記憶體(Memory) 都需作資料
型態(Data Types) 之宣告(Declare),以限制該記憶體儲存資
料的型態。
•
• 宣告如int a 時,設定記憶體名稱為a,用於儲存整數
(integer);宣告如char b 時,設定記憶體名稱為b,用於儲
存字元(character)。
範例7: 變數與物件之用法。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int i;
03 }
04 class Ex04_1_1 {
05 public static void main(String[] args) {
06
int j;
07
Mynumber a;
08
j = 3;
09
a = 5;
10
System.out.println("j = "+j);
11
System.out.println("a = "+a);
12 }
13 }
範例8: 內建資料型態、與建構資料型態之用法。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int i;
03 }
04 class Ex04_1_2 {
05 public static void main(String[] args) {
06
int j;
07
Mynumber a;
08
j=3;
09
a = new Mynumber();
10
a.i = 5;
11
System.out.println("j = "+j);
12
System.out.println("a.i = "+a.i);
13
}
14 }
4-2 基本資料型別(Primitive Types)
範例9: 字元(char) 變數宣告。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_2_1 {
02 public static void main (String[] argv) {
03
char ch;
04
ch = 'A';
05
System.out.println(“英文字母 = ”+ch);
06
ch = '\u0041';
07
System.out.println(“Unicode碼 = ”+ch);
08
ch = 65;
09
System.out.println(“ASCII十進位碼 = ”+ch);
10
ch = '中';
11
System.out.println(“中文字元 = ”+ch);
12
ch = '\u4E2D';
13
System.out.println(“中文Unicode碼 = ”+ch);
14
ch = 20013;
15
System.out.println(“中文十進位碼 = ”+ch);
16
ch = '\0';
17
System.out.println("特殊字元之空字元 = "+ch);
18
}
19 }
範例10: 位元組整數(byte) 變數宣告。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_2_2 {
02 public static void main (String[] argv) {
03
byte bt;
04
05
bt = 65;
System.out.println("數值 = "+bt);
06
07
bt = 'A';
System.out.println("字母A之ASCII十進位碼 = "+bt);
08
bt = '\0';
09
System.out.println("特殊字元之空字元碼 = "+bt);
10 }
11 }
範例11: 短整數(short) 變數宣告
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_2_3 {
02 public static void main (String[] argv) {
03
short st;
04
05
st = 65;
System.out.println("一般數值 = "+st);
06
07
st = 'A';
System.out.println("字母A之ASCII十進位碼 = "+st);
08
09
st = '中';
System.out.println("中文字元十進位碼 = "+st);
10
st = '\0';
11
System.out.println("特殊字元之空字元碼 = "+st);
12 }
13 }
範例12: 整數(int) 之變數宣告
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_2_4 {
02 public static void main (String[] argv) {
03
int in;
04
in = 65;
05
System.out.println(“一般數值 = ”+in);
06
in = 'A';
07
System.out.println(“英文字母執行結果 = ”+in);
08
in = '中';
09
System.out.println(“中文字元執行結果 = ”+in);
10
in = '\u4E2D';
11
System.out.println(“Unicode執行結果 = ”+in);
12
in = 047055;
13
System.out.println(“八進位執行結果 = ”+in);
14
in = 0x4E2D;
15
System.out.println(“十六進位執行結果 = ”+in);
16
in = '\0';
17
System.out.println("特殊字元執行結果 = "+in);
18 }
19 }
範例13: 長整數(long) 之變數宣告,以一個大於int資料型態範圍
長度之數值為指定值,觀察發生錯誤的原因。
•
•
•
•
•
•
•
•
•
01 class Ex04_2_5 {
02 public static void main (String[] argv) {
03
long lng;
04
lng = 0xFFFFFFFFF;
05
System.out.println("最右端無L之長整數 = "+lng);
06 }
07 }
範例14:長整數(long) 之變數宣告,於指定值最右端加置
“L”,觀察其執行結果。
•
•
•
•
•
•
•
•
•
01 class Ex04_2_5 {
02 public static void main (String[] argv) {
03
long lng;
04
lng = 0xFFFFFFFFFL;
05
System.out.println("最右端為L之長整數 = "+lng);
06 }
07 }
範例15: 浮點之變數宣告,當float變數指定值之最右端未
加置“F ” 或 “f ” 時,觀察發生錯誤的原因。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_2_6 {
02 public static void main (String[] argv) {
03
float ft;
04
double dft;
05
ft = 120.5;
06
System.out.println(“float指定值 = ”+ft);
07
ft = 1.205E2;
08
System.out.println(“float指定值 = ”+ft);
09
ft = 12050E-2;
10
System.out.println(“float指定值 = ”+ft);
11
dft = 120.5;
12
System.out.println(“double指定值 = ”+dft);
13
dft = 1.205E2;
14
System.out.println(“double指定值 = ”+dft);
15
dft = 12050E-2;
16
System.out.println("double指定值 = "+dft);
17 }
18 }
範例16: 浮點之變數宣告,當float變數指定值之最右端加置“F ”
或 “f ” 時,觀察其執行結果。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_2_6 {
02 public static void main (String[] argv) {
03
float ft;
04
double dft;
05
ft = 120.5f;
06
System.out.println(“float指定值 = ”+ft);
07
ft = 1.205E2f;
08
System.out.println(“float指定值 = ”+ft);
09
ft = 12050E-2f;
10
System.out.println(“float指定值 = ”+ft);
11
dft = 120.5;
12
System.out.println(“double指定值 = ”+dft);
13
dft = 1.205E2;
14
System.out.println(“double指定值 = ”+dft);
15
dft = 12050E-2;
16
System.out.println("double指定值 = "+dft);
17 }
18 }
範例17: 布林值之變數宣告。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_2_7 {
02 public static void main (String[] argv) {
03
boolean bn;
04
05
bn = true;
System.out.println("boolean指定值 = "+bn);
06
bn = false;
07
System.out.println("boolean指定值 = "+bn);
08 }
09 }
4-3 參考資料型別(Reference Types)
• 宣告之變數若無確定之長度,該變數型態是謂 “參
考型別(Reference Types)”。常用於Java程式中者有
三類:矩陣、字串、與建構物件。有關建構物件
變數之宣告,請參考範例7與範例8。
範例18: 矩陣之變數宣告。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int number;
03 }
04 class Ex04_3_1_1 {
05 public static void main(String[] args) {
06
int[ ] a;
07
Mynumber[ ] b;
08
09
10
11
12
a = new int[2];
a[0] = 10;
a[1] = 20;
System.out.println("a[0] = "+a[0]);
System.out.println("a[1] = "+a[1]);
範例18:續
•
•
•
•
•
•
•
•
•
13
b = new Mynumber[2];
14
b[0] = new Mynumber();
15
b[1] = new Mynumber();
16
b[0].number = 30;
17
b[1].number = 40;
18
System.out.println("b[0].number= "+b[0].number);
19
System.out.println("b[1].number= "+b[1].number);
20
}
21 }
範例19: 矩陣之變數宣告、及使用大括號 “{ }” 設
定矩陣各元素之指定值。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_3_1_2 {
02 public static void main (String[] argv) {
03
int[ ] f = {10,20};
04
int[ ] g;
05
g = new int[ ] {30,40};
06
07
08
09
10
11 }
System.out.println("f[0] = "+f[0]);
System.out.println("f[1] = "+f[1]);
System.out.println("g[0] = "+g[0]);
System.out.println("g[1] = "+g[1]);
}
範例20: 對稱多維矩陣變數之宣告。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int n;
03 }
04 class Ex04_3_2_1_1 {
06 public static void main(String[] args) {
07
int[ ][ ] a;
08
Mynumber[ ][ ] b;
09
10
11
12
13
14
15
16
17
a = new int[2][2];
a[0][0] = 10;
a[0][1] = 20;
a[1][0] = 30;
a[1][1] = 40;
System.out.println("a[0][0] = "+a[0][0]);
System.out.println("a[0][1] = "+a[0][1]);
System.out.println("a[1][0] = "+a[1][0]);
System.out.println("a[1][1] = "+a[1][1]);
範例20:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 }
b = new Mynumber[2][2];
b[0][0] = new Mynumber();
b[0][1] = new Mynumber();
b[1][0] = new Mynumber();
b[1][1] = new Mynumber();
b[0][0].n = 50;
b[0][1].n = 60;
b[1][0].n = 70;
b[1][1].n = 80;
System.out.println("b[0][0].n = "+b[0][0].n);
System.out.println("b[0][1].n = "+b[0][1].n);
System.out.println("b[1][0].n = "+b[1][0].n);
System.out.println("b[1][1].n = "+b[1][1].n);
}
範例21: 對稱多維矩陣變數之宣告、及使用
大括號 “{ }” 設定矩陣各元素之指定值。
•
• class Ex04_3_2_1_2 {
•
public static void main (String[] argv) {
•
int[][] a = {{10,20},{30,40}};
•
•
System.out.println("a[0][0] = "+a[0][0]);
•
System.out.println("a[0][1] = "+a[0][1]);
•
System.out.println("a[1][0] = "+a[1][0]);
•
System.out.println("a[1][1] = "+a[1][1]);
•
}
• }
範例22: 非對稱多維矩陣變數宣告。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_3_2_2_1 {
02 public static void main(String[] args) {
03
int[ ][ ] a;
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18 }
a = new int[2][ ];
a[0] = new int[2];
a[1] = new int[3];
a[0][0] = 10;
a[0][1] = 20;
a[1][0] = 30;
a[1][1] = 40;
a[1][2] = 50;
System.out.println("a[0][0] = "+a[0][0]);
System.out.println("a[0][1] = "+a[0][1]);
System.out.println("a[1][0] = "+a[1][0]);
System.out.println("a[1][1] = "+a[1][1]);
System.out.println("a[1][2] = "+a[1][2]);
}
範例23: 非對稱多維矩陣變數之宣告、及使用大括號 “{ }”
設定矩陣各元素之指定值。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_3_2_2_2 {
02 public static void main (String[] argv) {
03
int[ ][ ] a = {{10,20},{30,40,50}};
04
05
06
07
08
09
10 }
System.out.println("a[0][0] = "+a[0][0]);
System.out.println("a[0][1] = "+a[0][1]);
System.out.println("a[1][0] = "+a[1][0]);
System.out.println("a[1][1] = "+a[1][1]);
System.out.println("a[1][2] = "+a[1][2]);
}
範例24: 字串之變數宣告。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex04_3_2 {
02 public static void main (String[] argv) {
03
String s;
04
05
s = "abcd";
System.out.println("s = "+s);
06
s = new String("wxyz");
07
System.out.println("s = "+s);
08 }
09 }
第五章
運算關係式(Expression)
5-1 簡介
•
• 電腦系統對我們人類之意義,可廣義歸納為:資料儲存(Store)、資
料運算(Calculation)、與資料傳輸(Transmission)。可見運算是電腦
系統之一個重要環節,本章將就Java之狹義運算式(Expressions) 作
詳細探討。
•
• 於離散數學曾定義:設有元素值a與b,若兩者之間存在某種關係
元R,即可以關係式 “aRb” 表示之。我們熟悉的關係元如:“等於
(=)”、“大於(>)”、“因此(→)”、“加(+)”、“乘(×)” 等均屬之。
•
• Java程式中之大部份敘述式(Statements),都是由運算關係式
(Expressions) 所組成。運算關係式(Expressions) 包括 “運算值
(Operands)” 與 “運算元(Operators)”,如2+3,運算值為2與3,運算
元為+。
5-2 指定運算元(Assignment Operators)
• 指定運算元以等號 “=” 表示之,等號之左端為變
數(Variable),右端為指定值(Assign Value)。系統將
右端之指定值給予左端之變數,指定值可以是一
個數值、可以是一個變數、亦可以是一個運算式。
範例25: 指定運算元之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_2 {
02 public static void main (String[] argv) {
03
int a, b, c, d;
04
05
06
07
a = 15;
b = 'A';
System.out.println("數值 a = "+a);
System.out.println("字元值 b = "+b);
08
09
c = b;
System.out.println("變數值 c = "+c);
10
d = a + b;
11
System.out.println("運算式值 d = "+d);
12 }
13 }
5-3 算術運算元(Arithmetic Operators)
• 算術運算元包括:加、減、乘、除、餘數,分別
以+、-、*、/、% 表示之,其運算值之資料型態必
需為 { byte, int, short, long, float, double},否則無
法計算,有關資料型態之轉換,將於爾後再詳述。
範例26: 算術運算元之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_3_1 {
02 public static void main (String[] argv) {
03
int a = 15, b = 2, c;
04
05
06
07
08
09
10
11
12
13
14
15 }
c = a + b;
System.out.println(“加法值 c = ”+c);
c = a - b;
System.out.println(“減法值 c = ”+c);
c = a * b;
System.out.println(“乘法值 c = ”+c);
c = a / b;
System.out.println(“除法值 c = ”+c);
c = a % b;
System.out.println("餘數值 c = "+c);
}
範例27: 算術運算元與複合等號之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_3_2 {
02 public static void main (String[] argv) {
03
int a, b = 2;
04
05
06
a = 15;
a += b;
System.out.println("加法值 a = "+a);
07
08
09
a = 15;
a -= b;
System.out.println("減法值 a = "+a);
範例27:續
•
•
•
•
•
•
•
•
•
•
•
•
•
10
11
12
a = 15;
a *= b;
System.out.println("乘法值 a = "+a);
13
14
15
a = 15;
a /= b;
System.out.println("除法值 a = "+a);
16
17
18
19
20 }
a = 15;
a %= b;
System.out.println("除法值 a = "+a);
}
5-4 遞增/遞減運算元
(Increment/Decrement Operators)
• 一般來言,遞增/遞減運算元(Increment/Decrement
Operator) 用於迴圈(Loop),每迴圈一次,變數值加1、或
減1。表示方式可分兩類:前置式(Prefix) 如++a、--a,與後
置式(Postfix) 如a++、a--。
範例28遞增/遞減運算元之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_4 {
02 public static void main (String[] argv) {
03
int a;
04
05
a = 10;
System.out.println("前置遞增 a = "+ ++a);
06
07
a = 10;
System.out.println("後置遞增 a = "+ a++);
08
09
a = 10;
System.out.println("前置遞減 a = "+ --a);
10
a = 10;
11
System.out.println("後置遞減 a = "+ a--);
12 }
13 }
5-5 比較運算元(Compare Operators)
• 比較運算元(Compare Operators) 用於測試兩個運算值
(Operands) 的大小關係,並回傳一個布林值(Boolean Value)。
•
• 常用的比較運算元(Compare Operators) 有:相等(= =)、不
相等(! =)、大於(>)、小於(<)、大於等於(> =)、小於等於(<
=)。
範例29: 比較運算元之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_5 {
02 public static void main (String[] argv) {
03
int a = 3, b = 2;
04
05
06
07
08
09
10
11 }
System.out.println("測試 (a == b) = "+ (a==b));
System.out.println("測試 (a != b) = "+ (a!=b));
System.out.println("測試 (a > b) = "+ (a>b));
System.out.println("測試 (a < b) = "+ (a<b));
System.out.println("測試 (a >= b) = "+ (a>=b));
System.out.println("測試 (a <= b) = "+ (a<=b));
}
5-6 邏輯運算元(Logical Operators)
範例30: 邏輯運算元之應用。
•
•
•
•
•
•
•
•
01 class Ex05_6_1 {
02 public static void main (String[] argv) {
03
04
05
06
07 }
System.out.println("測試 (false & true) = "+ (false & true));
System.out.println("測試 (true | false) = "+ (true | false));
System.out.println("測試 (!true) = "+ (! true));
}
範例31: 短路(Short Circuit) 邏輯運算元之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_6_2 {
02 public static void main (String[] argv) {
03
int a;
04
05
06
07
08
09
10
11
12
13
14
15
16
17 }
a = 3;
System.out.println("測試 (true && (++a > 0)) = "+ (true && (++a > 0)));
System.out.println(“測試是否有執行 ++a: ”+ a);
a = 3;
System.out.println("測試 (false && (++a > 0)) = "+ (false && (++a > 0)));
System.out.println(“測試是否有執行 ++a: ”+ a);
a = 3;
System.out.println("測試 (true || (++a > 0)) = "+ (true || (++a > 0)));
System.out.println(“測試是否有執行 ++a: ”+ a);
a = 3;
System.out.println("測試 (false || (++a > 0)) = "+ (false || (++a > 0)));
System.out.println("測試是否有執行 ++a: "+ a);
}
5-7 位元運算元(Bitwise Operators)
• 數值以2進位表示時,每一個位置之0或1佔用一個
位元(Bit),執行如此形態之運算元是謂 “位元運算
元(Bitwise Operators)”。常用的位元運算元有 “補
數運算元(Complement Bitwise Operators)”、“位移
運算元(Shift Bitwise Operators)”、與 “位元邏輯運
算元(Logical Bitwise Operators)”。
範例34: 補數運算元之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_7_1 {
02 public static void main (String[] argv) {
03
int a, b;
04
a = 3;
05
System.out.println("執行前之 a值: "+ a);
06
a = ~a;
07
System.out.println(“1的補數執行後之 a值: ”+ a);
08
a = -3;
09
System.out.println("執行前之 a值: "+ a);
10
a = ~a;
11
System.out.println(“1的補數執行後之 a值: ”+ a);
12
b = 3;
13
System.out.println("執行前之 b值: "+ b);
14
b = ~b+1;
15
System.out.println(“2的補數執行後之 b值: ”+ b);
16
b = -3;
17
System.out.println("執行前之 b值: "+ b);
18
b = ~b+1;
19
System.out.println("2的補數執行後之 b值: "+ b);
20 }
21 }
範例41: 位移運算元之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_7_2_1 {
02 public static void main (String[] argv) {
03
int a, b;
04
05
06
a = 4;
b = a>>1;
System.out.println("正數測試右移運算元 >>: "+ b);
07
08
09
a = -4;
b = a>>1;
System.out.println("負數測試右移運算元 >>: "+ b);
範例41:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
10
11
12
a = 4;
b = a<<1;
System.out.println("正數測試左移運算元 <<: "+ b);
13
14
15
a = -4;
b = a<<1;
System.out.println("負數測試左移運算元 <<: "+ b);
16
17
18
a = 4;
b = a>>>1;
System.out.println("正數測試0值右移運算元 >>>: "+ b);
19
20
21
22
23 }
a = -4;
b = a>>>1;
System.out.println("負數測試0值右移運算元 >>>: "+ b);
}
範例43: 大於32位元位移之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_7_2_2 {
02 public static void main (String[] argv) {
03
int a, b;
04
05
06
a = 4;
b = a>>1;
System.out.println("正數測試右移運算元 >>: "+ b);
07
08
09
a = 4;
b = a>>33;
System.out.println("測試大於32位元之位移: "+ b);
10
11
12
a = -4;
b = a>>1;
System.out.println("負數測試右移運算元 >>: "+ b);
13
14
15
a = -4;
b = a>>33;
System.out.println("測試大於32位元之位移: "+ b);
範例43:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
16
17
18
a = 4;
b = a<<1;
System.out.println("正數測試左移運算元 <<: "+ b);
19
20
21
a = 4;
b = a<<33;
System.out.println("測試大於32位元之位移: "+ b);
22
23
24
a = -4;
b = a<<1;
System.out.println("負數測試左移運算元 <<: "+ b);
25
26
27
28
29 }
a = -4;
b = a<<33;
System.out.println("測試大於32位元之位移: "+ b);
}
範例47: 位元邏輯運算元之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_7_3 {
02 public static void main (String[] argv) {
03
int a = 9, b = 10, c;
04
05
c = a & b;
System.out.println("測試運算元 &: "+ c);
06
07
c = a | b;
System.out.println("測試運算元 |: "+ c);
08
c = a ^ b;
09
System.out.println("測試運算元 ^: "+ c);
10 }
11 }
5-8 資料轉型(Type Conversion)
• 較小範圍資料型態之變數可自動轉換成較大範圍
之資料型態,亦即小範圍之變數可輕易置入大範
圍之容器內,是謂 “放大轉型(Widening
Conversion)” 或稱 “隱性轉型(Implicit Casting)”。
• 較大範圍資料型態之變數需經過強迫手段,才可
轉換成較小範圍之資料型態,如圖5-8-1之反箭頭
方向,亦即大範圍之變數無法輕易置入小範圍之
容器內,是謂 “縮小轉型(Narrowing Conversion)”
或稱 “顯性轉型(Explicit Casting)”。
範例49: 資料變數自動轉型之應用。
•
•
•
•
•
•
•
•
•
•
01 class Ex05_8_1 {
02 public static void main (String[] argv) {
03
byte bt;
04
short sh;
05
int in;
06
long lg;
07
float ft;
08
double db;
範例49:續
•
•
•
•
•
•
•
•
•
•
•
•
•
09
10
11
12
13
14
15
16
17
18
19
20
21 }
bt = 97;
sh = bt;
System.out.println("short<--byte:"+sh+"<--"+bt);
in = sh;
System.out.println("int<--short:"+in+"<--"+sh);
lg = in;
System.out.println("long<--int:"+lg+"<--"+in);
ft = lg;
System.out.println("float<--long:"+ft+"<--"+lg);
db = ft;
System.out.println("double<--float:"+db+"<--"+ft);
}
範例50: 資料變數強迫轉型之應用。
•
•
•
•
•
•
•
•
•
•
01 class Ex05_8_2 {
02 public static void main (String[] argv) {
03
byte bt;
04
short sh;
05
int in;
06
long lg;
07
float ft;
08
double db;
範例50:續
•
•
•
•
•
•
•
•
•
•
•
•
•
09
db = 97.0;
10
ft = (float)db;
11
System.out.println("float<--double:"+ft+"<--"+db);
12
lg = (long)ft;
13
System.out.println("long<--float:"+lg+"<--"+ft);
14
in = (int)lg;
15
System.out.println("int<--long:"+in+"<--"+lg);
16
sh = (short)in;
17
System.out.println("short<--int:"+sh+"<--"+in);
18
bt = (byte)sh;
19
System.out.println("bt<--short:"+bt+"<--"+sh);
20 }
20 }
5-9 條件運算元(Conditional Operators)
• 當Java程式執行到邏輯決策選擇時,我們使用條
件運算式,條件運算式是由運算元符號 “問號(?) ”、
與 “ 冒號(:) ” 組成,其格式為:
•
•
Max = ( (a > b) ? a : b);
範例51: 條件式之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex05_9 {
02 public static void main (String[] argv) {
03
int a=3, b=2, M, N;
04
05
M = ((a>b) ? a : b);
System.out.println("M = "+M);
06
07
08
09
10
11
12 }
if (a>b)
N = a;
else
N = b;
System.out.println("N = "+N);
}
第六章
流程控制(Control Flow)
6-1 簡介
•
• 一般來言,系統執行程式碼,是依其排列之次序,由
左向右、由上向下,依序執行,有時會因需要,以決
策(Decisions)、廻圈(Loops)、或跳離(Break) 等方式執
行程式碼,凡引導執行程式碼之流程次序,是謂 “流
程控制(Control Flow)”。
•
• 於Java程式中,常用之流程控制為 “決策流程控制
(Decision Control Flow)” 與 “廻圈流程控制(Loop Control
Flow)”。前者使用if…else、else if、switch…case敘述式
(Statements);後者使用while、do…while、for廻圈。
6-2決策流程控制(Decision Control Flow)
• 如5-9節述及,決策流程控制(Decision Control Flow)
包括三個部份:條件運算式(Condition Expression)、
真值敘述式(True Statements)、偽值敘述式(False
Statements)。常用之決策流程控制格式有:
if…else、else if、與switch…case。
6-2-1 if…else決策
• if (condition expression)
•
{ true statements;}
• else
•
{ false statements;}
6-2-2 else if決策
• if (expression_1)
•
statement_1;
•
else if (expression_2)
•
statement_2;
•
else if (expression_3)
•
statement_3;
•
else
•
statement_4;
範例55:else if區塊鏈、與多重多層決策之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_2_2 {
02 public static void main (String[] argv) {
03 int a = 3;
04 if (a == 1)
05
System.out.println("a is 1");
06
else if (a == 2)
07
System.out.println("a is 2");
08
else if (a == 3)
09
System.out.println("a is 3");
10
else
11
System.out.println("a is others");
12 }
13 }
6-2-3 switch…case決策
• switch (expression) {
•
case expression_value_1:
•
statements_1;
•
break;
•
case expression_value_2:
•
statements_2;
•
break;
•
case expression_value_3:
•
statements_3;
•
break;
•
default:
•
statements_4;
•
}
範例56:switch…case區塊鏈多重多層決策之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_2_3_1 {
02 public static void main (String[] argv) {
03 int a = 3;
04 switch (a) {
05
case 1:
06
System.out.println("a is 1");
07
break;
08
case 2:
09
System.out.println("a is 2");
10
break;
11
case 3:
12
System.out.println("a is 3");
13
break;
14
default:
15
System.out.println("a is others");
16 }
17 }
18 }
範例57:字串方法程序length()、與switch…case區塊鏈多重多層決策之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_2_3_2 {
02 public static void main (String[] argv) {
03 String s = "abc";
04 switch (s.length()) {
05
case 1:
06
System.out.println("length of s is 1");
07
break;
08
case 2:
09
System.out.println("length of s is 2");
10
break;
11
case 3:
12
System.out.println("length of s is 3");
13
break;
14
default:
15
System.out.println("length of s is others");
16 }
17 }
18 }
6-3廻圈流程控制(Loop Control Flow)
• Java程式常使用的廻圈有while、do…while、for廻
圈(Loops),當測試條件為True時,繼續執行廻圈,
否則跳離廻圈。
範例58:while廻圈之應用。
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_3_1 {
02 public static void main (String[] argv) {
03 int a = 1;
04
05
06
07
08 }
09 }
while (a <= 3) {
System.out.println("a = : " + a);
a++;
}
範例59:do…while廻圈之應用。
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_3_2 {
02 public static void main (String[] argv) {
03 int a = 1;
04
05
06
07
08 }
09 }
do {
System.out.println("a = : " + a);
a++;
} while (a <= 3);
範例60:for廻圈之應用。
•
•
•
•
•
•
•
•
•
01 class Ex06_3_3 {
02 public static void main (String[] argv) {
03 int a;
04 for(a=1; a<=3; a++)
05
System.out.println("a = : " + a);
06 }
07 }
6-4 break與continue
• 在Java程式廻圈中,break用於跳出廻圈區塊,並且不再執
行該次廻圈內之重複執行式(Iteration Expression);continue
用於跳出該次廻圈,但並未跳出區塊,仍繼續執行該次廻
圈內之重複執行式。
範例63:break在廻圈之應用。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_4_1 {
02 public static void main (String[] argv) {
03 int a;
04 for(a=1; a<=5; a++) {
05
if(a==3)
06
break;
07
System.out.println("a = : " + a);
08 }
09 }
10 }
範例64:continue在廻圈之應用。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_4_2 {
02 public static void main (String[] argv) {
03 int a;
04 for(a=1; a<=5; a++) {
05
if(a==3)
06
continue;
07
System.out.println("a = : " + a);
08 }
09 }
10 }
範例65:break與廻圈標籤之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_4_3 {
02 public static void main (String[] argv) {
03
int a, b;
04 L1: for(a=1; a<=2; a++) {
05
System.out.println("a = : " + a);
06 L2: for(b=1; b<=5; b++) {
07
if(b==3)
08
break L2;
09
System.out.println("b = : " + b);
10
}
11
}
12 }
13 }
範例66:continue與廻圈標籤之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_4_4 {
02 public static void main (String[] argv) {
03
int a, b;
04 L1: for(a=1; a<=2; a++) {
05
System.out.println("a = : " + a);
06 L2: for(b=1; b<=5; b++) {
07
if(b==3)
08
continue L2;
09
System.out.println("b = : " + b);
10
}
11
}
12 }
13 }
範例67:標籤之錯誤應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex06_4_5 {
02 public static void main (String[] argv) {
03
int a, b;
04 L1: b=1;
05
for(a=1; a<=5; a++) {
06
if(a==3)
07
break L1;
08
System.out.println("a = : " + a);
09
}
10 }
11 }
第七章
物件概念(Object Concepts)
7-1 簡介
•
• 於第三章,為了向初學讀者介紹Java程式之架構,已簡略
地描述物件之概念,在Java環境中,一個類別程序(Class
Procedure) 就是一個物件。Java檔案包含多個類別程序,
這些類別程序組成的物件,亦就是Java檔案的基礎物件元
素。本章將再詳述物件之變數、物件之產生、物件之應用、
與物件區塊等。
7-2 類別程序(Class Procedures) 與物件(Object)
• Java是物件導向語言(Object Oriented Language),
在程式設計上,須隨時圍繞著物件之觀點亦步亦
趨,但物件又是何物?這亦是本章要敘述的核心,
而本節將定義 “物件(Object)” 為何?
範例68: 簡介主體類別程序之地位、與主導複製及使用檔
案內其他類別程序產生的新物件。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int number;
03 }
04 class Ex07_2_3 {
05 public static void main(String[] args) {
06
Mynumber a= new Mynumber();
07
a.number= 10;
08
System.out.println("a.number= "+a.number);
09 }
10 }
7-3 內建物件(Built Objects) 與建構物件
(Constructed Objects)
• 如前述,我們已認識到所有的資料型態(Data Types) 都是類
別物件,源自各自之類別程序(Class Procedures)。常用的
資料型態(如int、char、float、boolean、String等) 是由系統
彙整複製之物件,宣告變數可直接被使用,是謂 “內建物
件(Built Objects)”;另外源自自行設計類別程序之資料型
態物件,是謂 “建構物件(Constructed Objects)”,如範例68
之Mynumber,其所宣告之變數不可直接被使用,必須經
過複製新物件之過程,才可被使用。
範例69內建物件、與建構物件之差異。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int i;
03 }
04 class Ex04_1_2 {
05 public static void main(String[] args) {
06
int j;
07
Mynumber a;
08
09
10
11
12
13
}
14 }
j=5;
a = new Mynumber();
a.i = 10;
System.out.println("j = "+j);
System.out.println("a.i = "+a.i);
7-4 區塊(Block)
• Java程式是以區塊(Block) 為組織基礎單位,每一區塊單位
以大括號涵蓋其範圍,各區塊彼此形成上下隸屬、左右同
儕的關係。
•
• 外部區塊為上司,內部區塊為下屬,平輩而互不隸屬的區
塊是為同儕。
範例70:系統為了節省時間與空間,每一區塊並非隨時都
存在的,只有當被執行時才存在。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex07_4_1 {
02 public static void main(String[] args) {
03
04
05
{ int a = 3;
System.out.println("Block A and a = " + a);
}
06
07
08
{ int b = 5;
System.out.println("Block B and b = " + b);
}
09 }
10}
範例71:兩個互不相關的區塊,可宣告相同名稱之變數。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex07_4_2 {
02 public static void main(String[] args) {
03
04
05
{ int a = 3;
System.out.println("Block A and a = " + a);
}
06
07
08
{ int a = 5;
System.out.println("Block B and a = " + a);
}
09 }
10 }
範例72:外部區塊與內部區塊不得有相同名稱之宣告變數。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex07_4_3 {
02 public static void main(String[] args) {
03
04
05
06
07
08 }
09 }
{ int a = 3;
{ int a = 5;
System.out.println("a = " + a);
}
}
範例73:內部區塊可使用外部區塊之宣告變數。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex07_4_4 {
02 public static void main(String[] args) {
03
04
05
06
07
08
09 }
10 }
{ int a = 3;
{ int b = 5;
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
範例74:外部區塊不得使用內部區塊之宣告變數。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex07_4_5 {
02 public static void main(String[] args) {
03
04
05
06
07
08
09 }
10}
{ int a = 3;
{ int b = 5;
}
System.out.println("a = " + a);
System.out.println("b = " + b);
}
7-5 生存變數(Instance Variable)
• 變數是源自類別程序,如果未建立成新物件,雖然已作變
數宣告,變數仍因其所屬的物件不存在而無法使用,這點
與其他程式語言有所不同。若要變數參與執行作為,必須
先建立該變數所屬的物件。
範例75:在類別程序內宣告之變數,無法直接使用。
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int n;
03 }
04 class Ex07_5_1 {
05 public static void main(String[] args) {
06
n = 10;
07
System.out.println("n = "+ n);
08 }
09 }
範例76:非生存區塊宣告之變數,無法直接使用。
•
•
•
•
•
•
•
•
•
01 class Ex07_5_2 {
02 int a;
03 public static void main(String[] args) {
04
a = 5;
05
System.out.println("a = "+ a);
06 }
07 }
7-6 類別變數(Class Variables)
• 於變數宣告時,增列前置關鍵字 “static” 即可將該變數一
直保持在生存狀態,並等待被執行,如:
•
static int a;
•
• 此時變數a將不因其所屬區塊、或物件之存在而存在,變
數a一直是存在的,唯一顧慮的是不得與當時任何其他變
數有相同之名稱。
範例77:類別變數之應用。
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 static int n;
03 }
04 class Ex07_6_1 {
05 public static void main(String[] args) {
06
Mynumber.n = 10;
07
System.out.println("n = "+ Mynumber.n);
08 }
09 }
範例78:變數在自身類別程序內宣告時,可標示所屬類別
物件之名稱(如範例77)、或直接被使用。
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex07_6_2 {
02 static int a;
03
04
05
public static void main(String[] args) {
Ex07_6_2.a = 5;
System.out.println("Ex07_6_2.a = "+ Ex07_6_2.a);
06
a = 10;
07
System.out.println("a = "+ a);
08 }
09 }
第八章
方法程序(Methods)
8-1 簡介
• Java語言的方法程序(Methods),猶如其他高階語言程式中
的副程式(Subroutines)或函數(Functions),是具有解決問題
功能的程式區塊,因Java為物件導向語言,故在類別、物
件等範疇下增添一些使用方法,這些方法都是學習Java的
基礎必讀,本章將以實例清晰地詳細介紹。
8-2 方法程序(Methods)
• 我們設計程式,是為了要籍程式的工作功能,幫助解決問
題。於其他程式語言、我們稱之謂 “副程式(Subroutine) /
函數(Function)”,於Java語言,我們稱之謂 “方法程序
(Methods)”。
•
• 為了方便,將常用的功能需求,先設計出一些內建副程式
(Subroutine) / 函數(Function),或Java之方法程序(Methods),
儲置於系統程式庫內,於爾後設計程式時,視需要,由主
程式呼叫有關的副程式/函數、或方法程序,組成一個功
能強大的工作群。
範例79:設有類別程序class Study內有方法程序addcredit()、
totalcredit()程式碼,試描述其執行功能:
•
•
•
•
•
01 class Study{
02 int credit = 0;
03 void addcredit(int i) {credit += i; }
04 int totalcredit() {return credit; }
05 }
範例80:主體類別程序如何呼叫使用方向程序?
•
•
•
•
•
•
•
•
•
•
•
•
01 class Study {
02 int credit=0;
03 void addcredit(int i) { credit += i; }
04 int totalcredit() { return credit; }
05 }
06 class Ex08_2_2 {
07 public static void main(String[] args) {
08
Study joe = new Study();
09
Study george = new Study );
範例80:續
•
•
•
•
•
•
•
•
•
•
•
•
10
11
joe.addcredit(12);
george.addcredit(9);
12
13
joe.addcredit(6);
george.addcredit(3);
14
System.out.println("joe studied:
"+joe.totalcredit()+"credites");
System.out.println("george studied:
"+george.totalcredit()+"credites");
15
16 }
17 }
8-3 生存方法程序(Instance Methods)
• 方法程序也是一樣,有其所屬之類別物件,當所
屬類別物件生存時,該方法程序才可被執行使用,
如此隨所屬類別物件生存而生存之方法程序是謂 “
生存方法程序(Instance Methods)”。
範例81:試敘述其中方法程序生存期之困擾。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Number {
02 int n = 0;
03 void addN(int i) { n = i; }
04 int getN() { return n; }
05 }
06 class Ex08_3_1 {
07 public static void main(String[] args) {
08
addN(10);
09
System.out.println("使用方法程序 getN: "+ getN());
10 }
11 }
範例82:試敘述其中方法程序生存期之困擾。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Number {
02 int n = 0;
03 void addN(int i) { n = i; }
04 int getN() { return n; }
05 }
06 class Ex08_3_1 {
07 public static void main(String[] args) {
08
Number N;
09
N.addN(10);
10
System.out.println("使用方法程序 N.getN: "+ N.getN());
11 }
12 }
範例82.5:生存方法程序(Instance Methods) 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Number {
02 int n = 0;
03 void addN(int i) { n = i; }
04 int getN() { return n; }
05 }
06 class Ex08_3_1 {
07 public static void main(String[] args) {
08
Number N = new Number();
09
10
N.addN(10);
System.out.println("使用方法程序 N.getN: "+ N.getN());
11
N.n = 20;
12
System.out.println("使用變數 N.n: "+ N.n);
13 }
14 }
8-5 建構子(Constructor)
• 於日常生活中,我們身邊的人、事、地、物都有一個代表
性的印像。張三是有能力的人、李四是浪漫的人、書房是
看書的房間等等。以書房為例,可以用作打牌、下棋、睡
覺等,但其代表性之主要功能仍是看書。
•
• Java語言亦有如上述之物件特性,一個類別程序含有多個
不同功能的方法程序,其中被選為代表性功能的方法程序
是謂該類別的 “建構子(Constructor)”。
範例84:建構子之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int n;
03
04
05
06
Mynumber() {
n = 3;
System.out.println("Here is Constructor and n = " + n);
}
07 int getnumber() { return n; }
08 }
09 class Ex08_5_1 {
10 public static void main(String[] args) {
11
Mynumber a = new Mynumber();
12
System.out.println("Here is main and a.getnumber() =
"+a.getnumber());
• 13
}
• 14 }
範例85:類別程序內,無法直接執行敘述式。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int n;
03
04
n = 3;
System.out.println("Here is Constructor and n = " + n);
05 int getnumber() { return n; }
06 }
07 class Ex08_5_2 {
08 public static void main(String[] args) {
09
Mynumber a = new Mynumber();
10
System.out.println("Here is main and a.getnumber() =
"+a.getnumber());
• 11
}
• 12 }
8-6 方法程序重載(Method Overload)
• Java語言也有類似之物件行為,類別內有多個方法程序,
名稱相同、功能相同,不同者為參數之不同:(1) 參數之
資料型態不同;(2) 參數之數量不同。當被呼叫執行時,
參數型態與數量均符合的方法程序,自動出面接受執行,
如此物件行為是謂 “方法程序重載(Method Overloading)”。
範例86:方法程序重載之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class adder{
02 int add(int a,int b){return a+b;}
03 double add(double i,double j){return i+j;}
04 int add(int p, int q, int r) {return p+q+r;}
05 }
06 class Ex08_6_1{
07 public static void main(String[] args){
08
int c;
09
double k;
10
int s;
11
adder ad= new adder();
範例86:續
•
•
•
•
•
•
•
•
•
•
12
13
c=ad.add(1, 2);
System.out.println("int c = " + c);
14
15
k=ad.add(3.3, 4.4);
System.out.println("double k = " + k);
16
s=ad.add(5, 6, 7);
17
System.out.println("int s = " + s);
18
}
19 }
範例87:建構子重載之應用。
•
•
•
•
•
•
•
•
•
•
01 class adder{
02 int c;
03 double k;
04
05
06
07
adder(int a, int b) {
c= a+b;
System.out.println("int c = "+ c);
}
範例87:續
•
•
•
•
•
•
•
•
•
•
•
•
08 adder(double i, double j){
09
k= i+j;
10
System.out.println("double k = "+ k);
11 }
12 }
13 class Ex08_6_2{
14 public static void main(String[] args){
15
adder add_int = new adder(2, 3);
16
adder add_double = new adder(2.2, 3.3);
17 }
18 }
8-7 public / private限制修飾子(Modifications)
• 在類別內宣告的變數(Variables)、或方法程序
(Methods) 均可前置限制修飾子(Modifications)
“public”、“private”,以限制其使用環境與時機。
範例88:變數或方法程序無前置限制修飾子(Default
Modifications) 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int i;
03 }
04 class Ex08_7_1 {
05 public static void main(String[] args) {
06
Mynumber M = new Mynumber();
07
08
09 }
10 }
M.i = 10;
System.out.println("Defualt Variable M.i = "+ M.i);
範例88:變數或方法程序無前置限制修飾子
(Default Modifications) 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 int i;
03 }
04 class Ex08_7_1 {
05 public static void main(String[] args) {
06
Mynumber M = new Mynumber();
07
08
09 }
10 }
M.i = 10;
System.out.println("Defualt Variable M.i = "+ M.i);
範例89:變數或方法程序前置限制修飾子public之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 public int i;
03 }
04 class Ex08_7_2 {
05 public static void main(String[] args) {
06
Mynumber M = new Mynumber();
07
08
09 }
10 }
M.i = 10;
System.out.println("Public Variable M.i = "+ M.i);
範例90:變數或方法程序前置限制修飾子private之錯誤應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 private int i;
03 }
04 class Ex08_7_3 {
05 public static void main(String[] args) {
06
Mynumber M = new Mynumber();
07
08
09 }
10 }
M.i = 10;
System.out.println("Private Variable M.i = "+ M.i);
範例91:變數或方法程序前置限制修飾子private時,只允
許自身物件內之方法程序使用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Study {
02 private int credit=0;
03 public void addcredit(int i) { credit += i; }
04 public int totalcredit() { return credit; }
05 }
06 class Ex08_7_4 {
07 public static void main(String[] args) {
08
Study joe = new Study();
09
Study george = new Study();
範例91:續
•
•
•
•
•
•
•
•
•
•
•
•
10
11
joe.addcredit(12);
george.addcredit(9);
12
13
joe.addcredit(6);
george.addcredit(3);
14
System.out.println("joe studied:
"+joe.totalcredit()+"credites");
System.out.println("george studied:
"+george.totalcredit()+"credites");
15
16 }
17 }
8-8 this代名詞
• Java因是物件導向語言,每一個類別猶如是一個物件
個體,除了有其本身的類別名稱外,亦可以 “this” 為
自己本身之代名詞,在程式設計上將可達到簡化的效
果,讀者將會於爾後複雜的網路程設計中,更感受到
其功效。
•
• “this” 之功能除了是其本身類別代名詞外,亦可作為
重載建構子間之呼叫橋樑,將更增進資料的安全性。
範例92:this之應用,為所屬類別物件(Class Objects) 之代名詞。
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
class Mynumber {
private int n;
public void setnumber(int i){this.n = i;}
public int getnumber(){return n;}
}
06 class Ex08_8_1 {
07 public static void main(String[] args) {
08
Mynumber M = new Mynumber();
09
M.setnumber(10);
10
System.out.println("M.getnumber : "+ M.getnumber());
• 11 }
• 12 }
範例93:this在建構子內,也是所屬類別物件之代名詞。
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 private int n;
03 public Mynumber(int i){this.n = i;}
04 public int getnumber(){return n;}
05 }
06 class Ex08_8_2_1 {
07 public static void main(String[] args) {
08
Mynumber M = new Mynumber(10);
09
System.out.println("M.getnumber : " + M.getnumber());
• 10 }
• 11 }
範例94:於必要時,this也是重載(Overload) 建構子的代名詞。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 private int n;
03
04
public Mynumber(int i){this.n = i;}
public Mynumber(int j, String s){this(j);}
05 public int getnumber(){return n;}
06 }
07 class Ex08_8_2_2 {
08 public static void main(String[] args) {
09
Mynumber M = new Mynumber(10, "abcde");
10
System.out.println("M.getnumber : " + M.getnumber());
11 }
12 }
範例95:當一個建構子以this() 呼叫另一個重載建構子時,
this() 必須置於該建構子的第一列。
•
•
•
•
•
•
•
•
•
•
01 class Mynumber {
02 private int n;
03
04
05
06
07
public Mynumber(int i){this.n= i;}
public Mynumber(int j, String s){
System.out.println("Here is a Overload
Constructor");
this(j);
}
範例95:續
•
•
•
•
•
•
•
•
•
•
08 public int getnumber(){return n;}
09 }
10 class Ex08_8_2_3 {
11 public static void main(String[] args) {
12
Mynumber M = new Mynumber(10, "abcde");
13
System.out.println("M.getnumber : " +
M.getnumber());
14 }
15 }
8-9 巢狀類別(Nested Class)
• 設有類別A、類別B,如果B存在於A之範圍內,則B是A之 “
次類別(Sub Class或Inner Class)”。如此排列稱為 “巢狀類別
(Nested Classes)”。
範例96:成員類別程序(Member Class) 產生新物件之步驟。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyClass {
02 class memb1 {
03
int i;
04
void seti() {i = 10;}
05
int geti() {return i;}
06 }
07 class memb2 {
08
int i;
09
void seti() {i = 20;}
10
int geti() {return i;}
11 }
12 }
範例96:續
•
•
•
•
•
•
•
•
•
•
•
•
•
13 class Ex08_9_1_1 {
14 public static void main(String[] args) {
15
MyClass M = new MyClass();
16
17
18
MyClass.memb1 m1 = M.new memb1();
m1.seti();
System.out.println("m1.geti : "+ m1.geti());
19
20
21
22 }
23 }
MyClass.memb2 m2 = M.new memb2();
m2.seti();
System.out.println("m2.geti : "+ m2.geti());
範例97:修飾子public/private與成員類別之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyClass {
02 public class memb1 {
03
int i;
04
void seti() {i = 10;}
05
int geti() {return i;}
06 }
07 private class memb2 {
08
int i;
09
void seti() {i = 20;}
10
int geti() {return i;}
11 }
12 }
範例97:續
•
•
•
•
•
•
•
•
•
•
•
•
•
13 class Ex08_9_1_2 {
14 public static void main(String[] args) {
15
MyClass M = new MyClass();
16
17
18
MyClass.memb1 m1 = M.new memb1();
m1.seti();
System.out.println("m1.geti : "+ m1.geti());
19
20
21
22 }
23 }
MyClass.memb2 m2 = M.new memb2();
m2.seti();
System.out.println("m2.geti : "+ m2.geti());
範例98:成員類別與宣告變數之關係。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex08_9_1_3 {
02
int i,j;
03
private MyMember memb;
04
05
06
07
08
09
10
11
12
13
14
class MyMember {
int m,n,o;
MyMember() {
i = 2;
Ex08_9_1_3.this.j = 4;
m = 12;
this.n = 14;
MyMember.this.o = 16;
}
public int getO() { return o; }
}
範例98:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
15
16
17
18
19
20
public Ex08_9_1_3 () {
memb = new MyMember();
System.out.println("m= "+memb.m + ","+
"n= "+memb.n + ","+
"o= "+memb.getO());
}
21
public int getJ() { return j; }
22
23
24
25
26
27 }
public static void main(String[] args) {
Ex08_9_1_3 a = new Ex08_9_1_3 ();
System.out.println("i= "+a.i +","+
"j= "+a.getJ());
}
範例99:區域類別與生存區塊之關係。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex08_9_2_1 {
02 int i;
03
04
05
06
07
08
09
10
11
12
public Ex08_9_2_1() {
class MyLocal {
int j;
public MyLocal(){
i = 5;
j= 10;
}
}
MyLocal L = new MyLocal();
}
13 public static void main(String[] args) {
14
Ex08_9_2_1 M = new Ex08_9_2_1();
15
System.out.println("j of Local: "+L.j);
16
System.out.println("i of Ex08_9_2_1: "+ M.i);
17 }
18 }
範例100:區域類別與生存區塊之關係。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex08_9_2_2 {
02 int i;
03
04
05
06
07
08
09
10
11
12
public Ex08_9_2_2() {
class MyLocal {
int j;
public MyLocal(){
i = 5;
j= 10;
}
}
MyLocal L = new MyLocal();
System.out.println("j of Local: "+L.j);
•
•
•
•
•
•
•
13
}
14 public static void main(String[] args) {
15
Ex08_9_2_2 M = new Ex08_9_2_2();
16
System.out.println("i of Ex08_9_2_2: "+ M.i);
17 }
18 }
範例101:區域類別不宜前置public、private等存取設定。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex08_9_2_3 {
02 int i;
03
04
05
06
07
08
09
10
11
12
public Ex08_9_2_3() {
public class MyLocal {
int j;
public MyLocal(){
i = 5;
j= 10;
}
}
MyLocal L = new MyLocal();
System.out.println("j of Local: "+L.j);
•
•
•
•
•
•
•
13
}
14 public static void main(String[] args) {
15
Ex08_9_2_3 M = new Ex08_9_2_3();
16
System.out.println("i of Ex08_9_2_3: "+ M.i);
17 }
18 }
第九章
基礎程式設計(Basic Programming)
9-1 簡介
•
• 本章將介紹Java程式之基礎設計,物件導向是以類別
物件為架構,以邏輯為擬態,模擬思維流程。為達到
擬人化思維之要求,在設計上涵蓋許多巧思。本章重
點在繼承類別(Inheritance)、抽象類別(Abstract)、與介
面類別(Interface),以最易學習之範例導引方式,介紹
類別物件間之關係,將我們人類之邏輯思維灌溉在程
式字裡行間,使電腦以我們熟悉的方法來解決問題。
9-2 繼承(Inheritance)
• 當一個類別B繼承(Inheritance) 自另一個類別A時,前者B為
子類別(Sub Class ),後者A為父類別(Supper Class),子類別
B繼承父類別A所擁有之所有內容內涵(如範例102)。繼承之
格式是以“extends” 將子類別繼承父類別,如:
•
class B extends A { }
範例102:子類別繼承父類別時,子類別將擁有父類別所有之功能內涵。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber{
02 private int number;
03 public void setNumber(int i) {
04
number = i;
05 }
06 public int getNumber() {
07
return number;
08 }
09 }
10 class E extends MyNumber {}
11 class Ex09_2_1 {
12 public static void main(String[] args) {
13 E a = new E();
14 a.setNumber(5);
15 System.out.println("a=: "+a.getNumber());
16 }
17 }
範例103:繼承物件各自獨立,其物件變數亦互不干擾。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber {
02 private int number=5;
03 public void setNumber(int i) { number = i; }
04 public int getNumber() { return number; }
05 }
06 class E1 extends MyNumber {}
07 class E2 extends MyNumber {}
08 class Ex09_2_2 {
09 public static void main(String[] args) {
10
E1 a1 = new E1();
11
E2 a2 = new E2();
12
a1.setNumber(10);
13
System.out.println("The number of a1 is: "+a1.getNumber());
14
System.out.println("The number of a2 is: "+a2.getNumber());
15
}
16 }
範例104:繼承物件雖各自獨立,但其類別變數將互相干擾。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber {
02 private static int number=5;
03 public void setNumber(int i) { number = i; }
04 public int getNumber() { return number; }
05 }
06 class E1 extends MyNumber {}
07 class E2 extends MyNumber {}
08 class S extends E2 {}
09 class Ex09_2_3 {
10 public static void main(String[] args) {
11
E1 a1 = new E1();
12
E2 a2 = new E2();
13
S s = new S();
14
s.setNumber(20);
15
16
17
18
}
19 }
System.out.println("The number of a1 is: "+a1.getNumber());
System.out.println("The number of a2 is: "+a2.getNumber());
System.out.println("The number of s is: "+s.getNumber());
範例105:當子類別繼承自父類別時,子類別除了繼承父類別所擁
有之內涵外,還可另添加本身之特性內涵。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber {
02 private int number;
03 public void setNumber(int i) { number = i; }
04 public int getNumber() { return number; }
05 }
06 class E extends MyNumber {
07 private String string;
08 public void setString(String s) { string = s; }
09 public String getString() { return string; }
10 }
範例105:續
•
•
•
•
•
•
•
•
•
•
•
•
11 class Ex09_2_4 {
12 public static void main(String[] args) {
13
E a = new E();
14
a.setNumber(5);
15
a.setString("I am in the SubClass");
16
17
18 }
19 }
System.out.println("The number of a is:
"+a.getNumber());
System.out.println("The string of a is:
"+a.getString());
範例106:當子類別的內容與父類別的內容有衝突時,子類別之內
容將覆蓋(Overwrite) 父類別之內容。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber {
02 int number;
03 public void setNumber() { number = 5; }
04 public int getNumber() { return number; }
05 }
06 class E extends MyNumber {
07 public void setNumber() { number = 10; }
08 }
09 class Ex09_2_5 {
10 public static void main(String[] args) {
11
E a = new E();
12
a.setNumber();
13
System.out.println("The number of a is: "+a.getNumber());
14 }
15 }
9-3 繼承(Inheritance) 與 限制修飾子(Modifications)
(1) 如果父類別之變數前置public,當被子類別繼承時,該變
數已是子類別之內涵,可在子類別內被使用(如範例107);
(2) 如果父類別之變數前置private,當被子類別繼承時,雖然
該變數已是子類別之內涵,但仍不得在子類別內被使用
(如範例108);
(3) 如果父類別之變數前置protected,該變數可被在同一包裹
內之其他類別採用,但不得被在不同包裹內之類別採用
(如範例109)。
範例107:父類別之變數前置public,當被子類別繼承時,該變數
可在子類別內被使用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {public int number;}
02 class E extends myNumber {
03 public void setNumber(int i) {number = i;}
04 public int getNumber() {return number;}
05 }
06 class Ex09_3_1 {
07 public static void main(String[] args) {
08
E a = new E();
09
a.setNumber(5);
10
System.out.println("The number of a is: "+a.getNumber());
11 }
12 }
範例108:父類別之變數前置private,不得在子類別
內被使用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {private int number;}
02 class E extends myNumber {
03 public void setNumber(int i) {number = i;}
04 public int getNumber() {return number;}
05 }
06 class Ex09_3_2 {
07 public static void main(String[] args) {
08
E a = new E();
09
a.setNumber(5);
10
System.out.println("The number of a is: "+a.getNumber());
11 }
12 }
範例109:父類別之變數前置protected,可被同一包裹內之類別採用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {protected int number;}
02 class E extends myNumber {
03 public void setNumber(int i) {number = i;}
04 public int getNumber() {return number;}
05 }
06 class Ex09_3_3 {
07 public static void main(String[] args) {
08
E a = new E();
09
a.setNumber(5);
10
System.out.println("The number of a is: "+a.getNumber());
11 }
12 }
9-4 super之應用
• super為父類別的代名詞,在執行super() 時,是直指父類
別之建構子(如範例111)。當子類別於本身建構子執行
super() 時,必須將super() 置於建構子之第一列,否則將發
生編譯錯誤 (如範例112)。
範例110:super是父類別的代名詞,this是本身所屬類別的代名詞。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {
02 int number= 5;
03 }
04 class E extends myNumber{
05 int number= 10;
06 public int getsuperNumber() {return super.number;}
07 public int getthisNumber() {return this.number;}
08 }
09 class Ex09_4_1 {
10 public static void main(String[] args) {
11
E a = new E();
12
13
14 }
15 }
System.out.println("The myNumber_number of a is: "
+a.getsuperNumber());
System.out.println("The E_number of a is: "+a.getthisNumber());
範例111:super() 為呼叫執行父類別之建構子。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {
02 private int number;
03 myNumber (int number) {this.number = number;}
04 public int getNumber() { return number; }
05 }
06 class E extends myNumber {
07 E() {super(5);}
08 }
09 class Ex09_4_2 {
10 public static void main(String[] args) {
11
E a = new E();
12
13 }
14 }
System.out.println("number= "+a.getNumber());
範例112:super() 應置於建構子之第一列。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {
02 private int number;
03 myNumber (int number) {this.number = number;}
04 public int getNumber() { return number; }
05 }
06 class E extends myNumber {
07 E() {
08
System.out.println("This is Constructor");
09
super(5);
10 }
11 }
12 class Ex09_4_3 {
13 public static void main(String[] args) {
14
E a = new E();
15
System.out.println("number= "+a.getNumber());
16 }
17 }
範例113:子類別建構子內未設置super(),系統會於第一列自動加
一行隱藏的super()。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class A {
02 A() {
03
System.out.println("A's constructor");}
04 }
05 class B extends A {
06 B() {
07
System.out.println("B's constructor");}
08 }
09 class C extends B {
10 C() {
11
System.out.println("C's constructor");}
12 }
13 class Ex09_4_4 {
14 public static void main(String[] args) {
15
C c = new C();
16 }
17 }
9-5 final之應用
• 我們曾解釋前置修飾子(Modifications)
public/private/protected在Java程式之意義,本節將
介紹另一修飾子final在Java之應用。
•
• 顧名思義,final之意義為 “最後者”,不得再繼續變
化使用,可前置於類別程序、方法程序、變數
範例114:當final前置於類別程序時,該類別程序不得被繼承。
•
•
•
01 final class myNumber {
02 int number= 5;
03 }
•
•
•
•
•
•
•
•
•
•
•
•
•
•
04 class E extends myNumber{
05 int number= 10;
06 public int getsuperNumber() {return super.number;}
07 public int getthisNumber() {return this.number;}
08 }
09 class Ex09_5_1 {
10 public static void main(String[] args) {
11
E a = new E();
12
System.out.println("The myNumber_number of a is: "
+a.getsuperNumber());
13
System.out.println("The E_number of a is: "+a.getthisNumber());
14 }
15 }
範例115:當final前置於方法程序時,該方法程序不得被覆蓋。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber {
02 int number;
03 final void setNumber() { number = 5; }
04 public int getNumber() { return number; }
05 }
06 class E extends MyNumber {
07 public void setNumber() { number = 10; }
08 }
09 class Ex09_5_2 {
10 public static void main(String[] args) {
11
E a = new E();
12
a.setNumber();
13
System.out.println("The number of a is: "+a.getNumber());
14 }
15 }
範例116:當final前置於變數時,該變數只可被設定一次。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex09_5_3 {
02 public static void main (String[] argv) {
03
final int i = 5;
04
final int j;
05
06
i = 10;
j = 20;
07
j = 30;
08
System.out.println("i = "+ i);
09
System.out.println("j = "+ j);
10 }
11 }
9-6 抽象類別(Abstract Classes)
• 抽象類別(Abstract Classes) 代表對某項內涵之關切,在程
式流程上不必亦無法執行該內涵,但在程式總體上有如此
一份內涵之地位。
•
• 抽象類別不得作執行,但可接受被繼承,再由繼承之子類
別執行其內涵概念,故抽象類別猶如是思想指導老師。
範例117:抽象類別(Abstract Classes) 不得用於產生新物件。
•
•
•
•
•
•
•
•
•
•
•
•
01 abstract class myNumber {
02
private int number = 5;
03
public int getNumber() { return number; }
04 }
05 class Ex09_6_1 {
06 public static void main(String[] args) {
07
myNumber a = new myNumber();
08
System.out.println(a.getNumber());
09 }
10 }
範例118:抽象類別用於被繼承,由繼承之子類別產生新物件。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 abstract class myNumber {
02
private int number = 5;
03
public int getNumber() { return number; }
04 }
05 class E extends myNumber {}
06 class Ex09_6_2 {
07 public static void main(String[] args) {
08
E a = new E();
09
System.out.println("the number of a= "+a.getNumber());
10 }
11 }
範例119:抽象方法程序不得有程式碼內容。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 abstract class myNumber {
02
public int number = 5 ;
03
public abstract int getNumber() {return number;};
04 }
05 class E extends myNumber {}
06 class Ex09_6_3 {
07 public static void main(String[] args) {
08
E a = new E();
09
System.out.println("the number of a= "+a.getNumber());
10 }
11 }
範例120:於繼承之子類別,應有一對應之方法程序,具有程式碼
內容,執行抽象方法程序功能。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 abstract class myNumber {
02
public int number = 5 ;
03
public abstract int getNumber();
04 }
05 class E extends myNumber {
06 public int getNumber() {return number;}
07 }
08 class Ex09_6_4 {
09 public static void main(String[] args) {
10
E a = new E();
11
System.out.println("the number of a= "+a.getNumber());
12 }
13 }
範例121:凡有抽象方法程序之類別,必須前置abstract。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myNumber {
02
public int number = 5 ;
03
public abstract int getNumber();
04 }
05 class E extends myNumber {
06 public int getNumber() {return number;}
07 }
08 class Ex09_6_5 {
09 public static void main(String[] args) {
10
E a = new E();
11
System.out.println("the number of a= "+a.getNumber());
12 }
13 }
9-7 介面類別(Interface Classes)
• 介面類別的功能型態猶如抽象類別,不得直接用於以
“new” 產生新物件,亦不得讓其他類別直接在此匯集,如
同抽象類別是一種內涵之關切,其內部之方法程序只有名
稱,較抽象類別更為嚴格地要求不得有行為程式碼,如:
•
Interface Myinterface { public void f(); }
• 介面類別Myinterface 前置 “interface”,內部方法程序f() 無
行為程式碼。
範例122:介面之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 interface myITF {public void f();}
02 class A implements myITF {
03 public void f() {System.out.println("myITF");}
04 }
05 class Ex09_7_1 {
06 public static void main(String[] args) {
07
A a = new A();
08
a.f();
09 }
10 }
範例123:同時以extends繼承類別程序、以implements承作介面。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 interface myITF {public void f();}
02 class myNumber {
03 public void g() {System.out.println("In myNumber");}
04 }
05 class A extends myNumber implements myITF {
06 public void f() {System.out.println("In myITF");}
07 }
08 class Ex09_7_2 {
09 public static void main(String[] args) {
10
A a = new A();
11
a.f();
12
a.g();
13 }
14 }
範例124:一個類別可同時承作(implements) 多個介面類別。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 interface myITF1 {public void f();}
02 interface myITF2 {public void g();}
03 class A implements myITF1, myITF2 {
04 public void f() {System.out.println("In myITF1");}
05 public void g() {System.out.println("In myITF2");}
06 }
07 class Ex09_7_3 {
08 public static void main(String[] args) {
09
A a = new A();
10
a.f();
11
a.g();
12 }
13 }
範例125:介面內之方法程序必須均無內容程式碼,且子類別內對
應之方法程序,必須另加置內容程式碼。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 interface myNumber {
02 public int number= 5;
03 public void setprint();
04 public int getNumber();
05 }
06 class E implements myNumber {
07 public void setprint() {System.out.println("In E");}
08 public int getNumber() {return number;}
09 }
10 class Ex09_7_4 {
11 public static void main(String[] args) {
12
E a = new E();
13
a.setprint();
14
System.out.println("the number of a= "+a.getNumber());
15 }
16 }
9-8 多重型態(Polymorphism)
• 新物件的產生是:(1)以資料型態宣告一個新物件變數;(2)
以“new” 啟動實體模型產生新物件;(3) 資料型態與實體模
型均屬同一類別。如:
•
myClass a = new myClass();
• myClass是類別,以其為資料型態宣告新物件變數a,再以
其為實體模型,由指令new啟動產生新物件,將新產生的
物件付予變數a。
範例126:多重型態(Polymorphism) 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myClass1 {
02 public void f() {System.out.println("In myClass1");
03 }
04 }
05 class myClass2 extends myClass1 {
06 public void f() {System.out.println("In myClass2");
07 }
08 }
09 class Ex09_8_1 {
10 public static void main(String[] args) {
11
myClass1 a = new myClass2();
12
a.f();
13 }
14 }
範例127:若資料型態類別內有符合名稱之方法程序,而實體模型
類別內無時,則執行資料型態類別內之方法程序。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myClass1 {
02 public void f() {System.out.println("In f of myClass1");
03 }
04 }
05 class myClass2 extends myClass1 {
06 public void g() {System.out.println("In g of myClass2");
07 }
08 }
09 class Ex09_8_2 {
10 public static void main(String[] args) {
11
myClass1 a = new myClass2();
12
a.f();
13 }
14 }
範例128:若資料型態類別內無符合名稱之方法程序,雖實體模型
類別內有,則仍不作任何執行。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myClass1 {
02 public void f() {System.out.println("In f of myClass1");
03 }
04 }
05 class myClass2 extends myClass1 {
06 public void g() {System.out.println("In g of myClass2");
07 }
08 }
09 class Ex09_8_2 {
10 public static void main(String[] args) {
11
myClass1 a = new myClass2();
12
a.g();
13 }
14 }
第十章
例外處理(Exceptions)
10-1 簡介
•
• 執行Java程式時,若遇錯誤程式碼,Java即以例外處理機
制處理,並顯示錯誤警語,提醒程式設計師有關事宜。有
關重大錯誤,由系統內建之錯誤警告常式執行,有關一般
性錯誤,則由程式設計師自訂警告程序執行。
•
• 系統內建之錯誤警告常式,可參考附錄A,包括:java.lang
之Error、java.lang之Exception、java.Util之Exception、
java.io之Exception、java.awt之Exception、java.net之
Exception。
10-2 try / catch / finally區段
• 於Java類別程式區塊內(除了一般程式碼區域外) 可分割成
數個特定意義的區段:(1)凡影響系統作業的程式碼必須要
在 “try區段” 執行;(2)如果try區段有引發編譯錯誤的程式
碼、或引發錯誤的邏輯行為,則由 “catch區段” 捕捉其錯
誤、顯示其錯誤訊息、及停止程式繼續執行;(3) “finally
區段” 之程式碼為必須要執行的流程。
圖10-2-1
範例129:建立網站與try/catch之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 public class Ex10_2_1_1 {
04 ServerSocket SS;
05 public Ex10_2_1_1() {
06
SS = new ServerSocket(1234);
07
System.out.println("Server created.");
08 }
09 public static void main(String args[]){
10
Ex10_2_1_1 ServerStart=new Ex10_2_1_1();
11 }
12 }
範例130:建立網站與try/catch之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 public class Ex10_2_1_2 {
04 ServerSocket SS;
05 public Ex10_2_1_2() {
06
try{
07
SS = new ServerSocket(1234);
08
System.out.println("Server created.");
09
}
10
catch(IOException e){
11
System.out.println(e.getMessage());
12
}
13 }
14 public static void main(String args[]){
15
Ex10_2_1_2 ServerStart=new Ex10_2_1_2();
16 }
17 }
範例131:不設try/catch區段之應用。
•
•
•
•
•
•
•
•
•
•
01 class Ex10_2_2_1 {
02 public static void main (String args[])
03
{
04
int x;
05
06
07
08 }
x = 10 / 0;
System.out.println("x= "+ x);
}
範例132:try/catch區段與例外事件資料庫之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex10_2_2_2 {
02 public static void main (String args[]) {
03
int x;
04
05
06
07
try {
x = 10 / 0;
System.out.println("x= "+ x);
}
08
catch (ArithmeticException e) {
09
System.out.println("In ArithmeticException:"+e.getMessage());
10
}
11 }
12 }
範例133:catch區段以Exception取代ArithmeticException之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex10_2_2_3 {
02 public static void main (String args[]) {
03
int x;
04
try {
05
x = 10 / 0;
06
System.out.println("x= "+ x);
07
}
08
catch (Exception e) {
09
System.out.println("In Exception :"+e.getMessage());
10
}
11 }
12 }
範例134:finally區段之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex10_2_3_1 {
02 public static void main (String args[]) {
03
int x;
04
05
06
07
try {
x = 10 / 0;
System.out.println("x= "+ x);
}
08
09
10
catch (Exception e) {
System.out.println("In Exception :"+e.getMessage());
}
11
finally {
12
System.out.println("In finally");
13
}
14 }
15 }
範例135:依圖10-2-1項3,設置try區段,不設置catch區段,如果
加置finally區段也可能編譯成功。
•
•
•
•
•
•
•
•
•
•
01 class Ex10_2_3_2 {
02 public static void main (String args[]) {
03
int x;
04
try {
05
x = 10 / 0;
06
System.out.println("x= "+ x);
07
}
08
}
09 }
範例136:依圖10-2-1項3,設置try區段,不設置catch區段,如果
加置finally區段也可能編譯不成功。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 public class Ex10_2_3_3 {
04 ServerSocket SS;
05 public Ex10_2_3_3() {
06
try{
07
SS = new ServerSocket(1234);
08
System.out.println("Server created.");
09
}
10 public static void main(String args[]){
11
Ex10_2_3_3 ServerStart=new Ex10_2_3_3();
12 }
13 }
10-3 throws之用法
• 前節曾述及,Java使用try/catch區段捕捉例外事件,尤其
在處理重要事件時,為了系統安全,更是要求程式碼必須
要置於try/catch區段內執行,否則將發生編譯錯誤。因此、
程式設計師在設計程式時,必須先考量是否要使用
try/catch區段。
• 為了減少程式設計師之困擾,可於方法程序(Methods) 或
建構子(Constructor) 宣告 “throws” 以取代try/catch之使用。
範例137:方法程序或建構子宣告 “throws” 以取代try/catch之使用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 public class Ex10_3_1 {
04 ServerSocket SS;
05 public Ex10_3_1() throws IOException {
06
SS = new ServerSocket(1234);
07
System.out.println("Server created.");
08 }
09 public static void main(String args[]) throws IOException{
10
Ex10_3_1 ServerStart=new Ex10_3_1();
11 }
12 }
範例138:方法程序或建構子宣告 “throws” 以取代try/catch之使用。
•
• 01 class Ex10_3_2 {
• 02 public static void main (String args[]) throws
ArithmeticException {
• 03
int x;
• 04
x = 10 / 0;
• 05
System.out.println("x= "+ x);
• 06 }
• 07 }
10-4 自訂例外處理物件
• 自訂例外處理物件可分為:
• (1)以內建例外處理類別產生自訂新物件;
• (2)自訂例外處理類別產生自訂新物件。
範例139:自訂匿名新例外處理物件。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex10_4_1_1 {
02 public static void main (String args[]) {
03
int x, y;
04
05
06
07
08
09
10
try {
x = 10;
y = 0;
if(y==0) throw new ArithmeticException("DIY Message");
x = 10 / 0;
System.out.println("x= "+ x);
}
11
catch (ArithmeticException e){
12
System.out.println("In ArithmeticException:"+e.getMessage());
13
}
14 }
15 }
範例140:自訂具名新例外處理物件。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex10_4_1_2 {
02 public static void main (String args[]) {
03
ArithmeticException f = new ArithmeticException("DIY Message");
04
int x, y;
05
06
07
08
09
10
try {
x = 10;
y = 0;
x = 10 / 0;
System.out.println("x= "+ x);
}
11
catch (ArithmeticException e){
12
System.out.println("In Built Message: "+e.getMessage());
13
System.out.println("In DIY Message: "+f.getMessage());
14
}
15 }
16 }
範例141:自訂預定訊息例外處理類別與匿名新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myException extends Exception {
02 myException() {
03
super("myException Message");
04 }
05 }
06 class Ex10_4_2_1 {
07 public static void main (String args[]) {
08
int x, y;
09
try {
10
x = 10;
11
y = 0;
12
if(y==0) throw new myException();
13
x = 10 / 0;
14
System.out.println("x= "+ x);
15
}
16
catch (myException e){
17
System.out.println("In myException: "+e.getMessage());
18
}
19 }
20 }
範例142:自訂預定訊息例外處理類別與具名新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myException extends Exception {
02 myException() {
03
super("myException Message");
04 }
05 }
06 class Ex10_4_2_2 {
07 public static void main (String args[]) {
08
myException f = new myException();
09
int x, y;
10
try {
11
x = 10;
12
y = 0;
13
x = 10 / 0;
14
System.out.println("x= "+ x);
15
}
16
catch (ArithmeticException e){
17
System.out.println("In Built Message: "+e.getMessage());
18
System.out.println("In myException Message: "+f.getMessage());
19
}
20 }
21 }
範例143:自訂機動訊息例外處理類別與匿名新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myException extends Exception {
02 myException(String msg) {
03
super(msg);
04 }
05 }
06 class Ex10_4_2_3 {
07 public static void main (String args[]) {
08
int x, y;
09
10
11
12
13
14
15
16
17
18
19 }
20 }
try {
x = 10;
y = 0;
if(y==0) throw new myException("DIY Message");
x = 10 / 0;
System.out.println("x= "+ x);
}
catch (myException e){
System.out.println("In myException: "+e.getMessage());
}
範例144:自訂機動訊息例外處理類別與具名新物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class myException extends Exception {
02 myException(String msg) {
03
super(msg);
04 }
05 }
06 class Ex10_4_2_4 {
07 public static void main (String args[]) {
08
myException f = new myException(“DIY Message”);
09
int x, y;
10
try {
11
x = 10;
12
y = 0;
13
x = 10 / 0;
14
System.out.println("x= "+ x);
15
}
16
catch (ArithmeticException e){
17
System.out.println("In Built Message: "+e.getMessage());
18
System.out.println("In myException Message: "+f.getMessage());
19
}
20 }
21 }
第十一章
Package包裹與Jar檔案
11-1 簡介
•
• 當Java程式編輯完成後,執行程式編譯,編譯完成後,我們將
發現程式中的每一類別都各自成為一個xxx.class檔。如果一個目
錄內有兩個檔案,編譯後將各自產生許多class檔,散落間插各
處,分不清那個class檔是屬於那一檔案,不易管理亦不易儲存。
•
• Java於程式設計時,可依需要設定package包裹,將一個Java程
式、或多個功能相同的Java程式,歸置於一個包裹內,同一包
裹內的類別在編譯完成後,歸置於同一目錄內,如此既易管理
亦易儲存。
•
• 為了可攜性,Java可將package包裹壓縮成jar檔案,因jar檔案本
身就是眾多class檔的集合,故可立即用於執行。
11-2類別(Class) 檔案
• 當Java程式經過編譯後,程式內的每一類別都將各自產生
一個xxx.class檔案,如前述,如此每一個class檔案就是一
個物件。
•
• 在Java程式檔案諸多class類別中,僅允許其中主體類別可
前置 “public”,用於爾後置入包裹之後,可讓其他程式取
用此包裹。
範例145:在Java程式諸多class類別中,僅允許其中主體類別可前
置public。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber{
02 private int number;
03 public void setNumber(int i) {
04
number = i;
05 }
06 public int getNumber() {
07
return number;
08 }
09 }
10 public class E extends MyNumber {}
11 public class Ex11_2_1 {
12 public static void main(String[] args) {
13 E a = new E();
14 a.setNumber(5);
15 System.out.println("a=: "+a.getNumber());
16 }
17 }
範例146:當Java程式經過編譯後,程式內的每一類別都將各自產
生一個xxx.class檔案。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber{
02 private int number;
03 public void setNumber(int i) {
04
number = i;
05 }
06 public int getNumber() {
07
return number;
08 }
09 }
10 class E extends MyNumber {}
11 public class Ex11_2_2 {
12 public static void main(String[] args) {
13 E a = new E();
14 a.setNumber(5);
15 System.out.println("a=: "+a.getNumber());
16 }
17 }
11-3 單一檔案包裹(Single File Package)
• 如前節所述,當Java程式編輯完成後,執行程式編譯,編
譯完成後,我們將發現程式中的每一個類別都各自成為一
個xxx.class檔。如果一個目錄內有多個程式檔案,編譯後
將各自產生許多class檔,散落間插各處,分不清那個class
檔屬於那一組功能,不易管理亦不易儲存。
範例147:於單一程式檔案中,如何建立包裹?如何編譯包裹?如
何執行包裹?。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02 class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
11 class E extends MyNumber {}
12 public class Ex11_3 {
13 public static void main(String[] args) {
14 E a = new E();
15 a.setNumber(5);
16 System.out.println("a=: "+a.getNumber());
17 }
18 }
11-4 多檔案包裹(Multi Files Package)
• 為了方便管理,我們可將多個Java程式檔案,以編譯方式
將各個類別程序,編譯成class檔案,置入同一包裹內。
範例148:設有檔案Ex11_4.java與MyNumber.java,其功能
為解釋於多個程式檔案中,如何建立共同包裹?如何編譯
共同包裹?如何執行共同包裹?。
•
• 檔案MyNumber.java:
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02 class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
範例148:續
• 檔案Ex11_4.java:
•
•
•
•
•
•
•
•
•
•
•
•
11 package myPackage;
12 class E extends MyNumber {}
13 public class Ex11_4 {
14 public static void main(String[] args) {
15 E a = new E();
16 a.setNumber(5);
17 System.out.println("a=: "+a.getNumber());
18 }
19 }
11-5包裹匯入(Import Package)
• 設定包裹的意義是將有關係的類別物件歸置在一起,便於
管理、便於攜帶。相對的,在設計Java程式中,為了設計
簡便,也應該可以使用別人已設計完成的包裹。
範例149:設有檔案Ex11_5.java與MyNumber.java,其功能
為解釋包裹匯入之應用。
•
• 檔案MyNumber.java:
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02 public class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
範例149:續
• 檔案Ex11_5.java:
•
•
•
•
•
•
•
•
•
•
•
•
01 import myPackage.MyNumber;
02 class E extends MyNumber {}
03 public class Ex11_5 {
04 public static void main(String[] args) {
05 E a = new E();
06 a.setNumber(5);
07 System.out.println("a=: "+a.getNumber());
08 }
09 }
11-6壓縮檔案(jar Files)
• 為了節省空間,我們可將Java程式檔案壓縮成jar檔案,當
Java程式經過編譯後,程式內的各類別將各自產生成
xxx.class檔,系統再將各class檔壓縮後儲存於jar檔案內。
範例150:如何建立包裹?如何建立jar檔?如何執行jar檔?。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02 class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
11 class E extends MyNumber {}
12 public class Ex11_6 {
13 public static void main(String[] args) {
14 E a = new E();
15 a.setNumber(5);
16 System.out.println("a=: "+a.getNumber());
17 }
18 }
11-7 jar檔與class檔之加入
• jar檔是由多個壓縮之class檔所組成,前節內容是將包裹內
的數個class檔,同時壓縮成一個jar檔。本節將介紹如何將
一個class檔壓縮加入jar檔?
範例151:將包裹內的class檔加入jar檔。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02 class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
11 class E extends MyNumber {}
12 public class Ex11_7_1 {
13 public static void main(String[] args) {
14 E a = new E();
15 a.setNumber(5);
16 System.out.println("a=: "+a.getNumber());
17 }
18 }
範例152:將非包裹內的class檔加入jar檔。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class MyNumber{
02 private int number;
03 public void setNumber(int i) {
04
number = i;
05 }
06 public int getNumber() {
07
return number;
08 }
09 }
10 class E extends MyNumber {}
11 public class Ex11_7_2 {
12 public static void main(String[] args) {
13 E a = new E();
14 a.setNumber(5);
15 System.out.println("a=: "+a.getNumber());
16 }
17 }
11-8 使用jar檔
• 我們已實作如何建立jar檔,讀者以後在Java程式設計上,
將會開發jar檔提供給其他程式使用;或是讀者自己在設計
程式時,使用到別人開發的jar檔。當設計提供其他程式使
用的jar檔時,壓縮至jar檔之主類別必須前置 “public”,否
則該jar檔無法被其他程式使用。在使用jar檔之設計上可分
為:(1) 匯入jar檔,(2) jar檔新物件。
範例153:設有檔案Ex11_8_1.java與MyNumber.java,其功能為解釋
匯入jar檔案之應用。
•
• 檔案MyNumber.java:
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02 public class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
範例153:續
• 檔案Ex11_8_1.java:
•
•
•
•
•
•
•
•
•
•
•
01 import myPackage.*;
02 public class Ex11_8_1 {
03 public static void main(String[] args) {
04
MyNumber a = new MyNumber();
05 a.setNumber(5);
06 System.out.println("a=: "+a.getNumber());
07 }
08 }
範例154:設有檔案Ex11_8_2.java與MyNumber.java,其功能為解釋
jar檔新物件之應用。
•
• 檔案MyNumber.java:
•
•
•
•
•
•
•
•
•
•
•
01 package myPackage;
02 public class MyNumber{
03 private int number;
04 public void setNumber(int i) {
05
number = i;
06 }
07 public int getNumber() {
08
return number;
09 }
10 }
範例154:續
• 檔案Ex11_8_2.java:
• 01 public class Ex11_8_2 {
• 02 public static void main(String[] args) {
• 03 myPackage.MyNumber a = new
myPackage.MyNumber();
•
• 04 a.setNumber(5);
• 05 System.out.println("a=: "+a.getNumber());
• 06 }
• 07 }
第十二章
輸入輸出串流
(Input/Output Streams)
12-1 簡介
•
• 在資料傳輸上,我們可將電腦的週邊設備(如印表機、螢幕、磁
碟等) 視為是檔案,資料從一個檔案傳送到另一個檔案,甚至可
將範圍擴大到無遠弗屆的網路上。
•
• 本章將介紹檔案、螢幕、鍵盤間之資料傳遞,至於網路上資料
的傳遞則於本書爾後作介紹。
•
• 無論是於何種設備、何種範圍,Java語言在資料傳遞上,均是
以串流方式傳遞,對當事程式來言,從來源設備輸入(Input) 資
料串流,再輸出(Output) 資料串流到指定的目的設備,完成資
料傳輸之執行。
12-2 指令參數(Command Parameters)
• 到目前為止,我們不曾對範例程式直接輸入訊息,於Java
程式,我們可利用指令參數(Command Parameters) 直接輸
入訊息。
• 常用的指令參數有:(1) 字串指令參數、與 (2) 整數指令參
數,前者以static String 宣告變數(如範例155);後者以static
int 宣告變數,且使用方法程序Integer.parseInt() (如範例
156)。
範例155:字串指令參數之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
01 public class Ex12_2_1 {
02 static String msg;
03
04
05
Ex12_2_1() {
System.out.println(msg);
}
06 public static void main(String[] args) {
07
msg = args[0];
08
Ex12_2_1 a = new Ex12_2_1();
09 }
10 }
範例156:整數指令參數之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 public class Ex12_2_2 {
02 static int num;
03
04
05
06
Ex12_2_2() {
num = num+1;
System.out.println(num);
}
07 public static void main(String[] args) {
08
num = Integer.parseInt(args[0]);
09
Ex12_2_2 a = new Ex12_2_2();
10 }
11 }
範例157:指令參數訊息之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 public class Ex12_2_3 {
02 static String msg;
03 static int num;
04
05
06
07
Ex12_2_3() {
System.out.println(msg);
System.out.println(num);
}
08 public static void main(String[] args) {
09
if(args.length < 2) {
10
System.out.println("Usage: java Ex12_2_3 [msg] [num]");
11
System.exit(1);
12
}
13
msg = args[0];
14
num = Integer.parseInt(args[1]);
15
Ex12_2_3 a = new Ex12_2_3();
16 }
17 }
12-3 檔案物件(File Objects)
• Java系統之java.io有其內建之檔案類別File.class,我們只要
於程式檔案加入import java.io.File,即可以此類別產生新
檔案物件,如:
•
File file = new File(fileName);
• 其中fileName為指定檔案之名稱,file為新產生之檔案物件。
範例158:檔案物件之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.File;
02 class Ex12_3_1 {
03 public static void main(String args[]) {
04
if (args.length < 1) {
05
System.out.println("Usage: java Ex12_3_1 [fileName]");
06
System.exit(1);
07
}
08
09
String fileName = args[0];
File f = new File(fileName);
10
System.out.println("The File is: ");
11
System.out.println(" File Name: " + f.getName());
12 }
13 }
範例159:檔案物件方法程序與例外事件處理之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.File;
import java.util.Date;
class Ex12_3_2 {
public static void main(String args[]) throws java.io.IOException {
if (args.length < 1) {
System.out.println("Usage: java Ex12_3_2 [fileName]");
System.exit(1);
}
String fileName = args[0];
File f = new File(fileName);
System.out.println("The File is: ");
System.out.println(" File Name: " + f.getName());
System.out.println(" File Name: " + f.getName());
System.out.println(" Canonical File Name: " + f.getCanonicalFile());
System.out.println(" canWritable: " + f.canWrite());
System.out.println(" Length: " + f.length());
System.out.println(" Hidden: " + f.isHidden());
System.out.println(" isFile: " + f.isFile());
System.out.println(" isDirectory: " + f.isDirectory());
System.out.println(" LastModified: " + new Date(f.lastModified()));
}
}
12-4 檔案輸入輸出串流
(File Input/Output Streams)
• Java程式之輸入輸出串流類別繼承自:(1)
InputStream/OutputStream、與(2) Reader/Writer,前者用
於位元傳輸,以位元組(Bytes) 為傳輸單位;後者以字元
(Character) 為傳輸單位,適用於以Unicode編碼之文字(如
中文等亞洲語系)。
12-5 FileInputStream與FileOutputStream
• 類別FileInputStream繼承自InputStream;類別
FileOutputStream繼承自OutputStream,用於檔案
資料傳遞。
範例160:FileInputStream之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex12_5_1 {
03 public static void main(String args[]) throws Exception {
04
int i;
05
06
07
08
if (args.length < 1) {
System.out.println("Usage: java Ex12_5_1 [fileName]");
System.exit(1);
}
09
10
String fileName = args[0];
FileInputStream fis=new FileInputStream(fileName);
11
while((i = fis.read()) != -1) {
12
System.out.print((char)i);
13
}
14 }
15 }
範例161:FileOutputStream之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex12_5_2 {
03 public static void main(String args[]) throws Exception {
04
if (args.length < 1) {
05
System.out.println("Usage: java Ex12_5_2 [fileName]");
06
System.exit(1);
07
}
08
09
String fileName = args[0];
FileOutputStream fos=new FileOutputStream(fileName);
10
String line = "Test for FileOutputStream 中文測試";
11
fos.write(line.getBytes());
12
fos.close();
13 }
14 }
範例162:以FileInputStream / FileOutStream將一個檔案之內容傳遞至另一個檔案內。
•
•
•
•
•
01 import java.io.*;
•
•
•
•
•
•
•
•
05
06
07
08
09
10
11
12
•
•
•
•
•
13 while((i=fis.read()) !=-1) {
14
fos.write(i);
15 }
16 }
}
02 class Ex12_5_3 {
03 public static void main(String args[]) throws Exception {
04 int i;
if (args.length < 2) {
System.out.println("Usage: java Ex12_5_3 [infileName] [outfileName]");
System.exit(1);
}
String infileName = args[0];
String outfileName = args[1];
FileInputStream fis=new FileInputStream(infileName);
FileOutputStream fos=new FileOutputStream(outfileName);
12-6 DataInputStream與DataOutputStream
• 使用DataInputStream / DataOutputStream時,須與其父類
別FileInputStream / FileOutputStream 搭配使用。
範例163:FileInputStream / DataInputStream之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex12_6_1 {
03 public static void main(String args[])throws Exception {
044 int i;
05
06
07
08
if (args.length < 1) {
System.out.println("Usage: java Ex12_6_1 [fileName]");
System.exit(1);
}
09
10
11
String fileName = args[0];
FileInputStream fis=new FileInputStream(fileName);
DataInputStream dis = new DataInputStream(fis);
12 while((i=dis.read()) !=-1) {
13
System.out.print((char)i);
14 }
15 }
16 }
範例164:FileOutputStream / DataOutputStream之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex12_6_2 {
03 public static void main(String args[])throws Exception {
04 if (args.length < 1) {
05
System.out.println("Usage: java Ex12_6_2 [fileName]");
06
System.exit(1);
07 }
08
09
10
String fileName = args[0];
FileOutputStream fos=new FileOutputStream(fileName);
DataOutputStream dos = new DataOutputStream(fos);
11 String line= "Test for DataOutputStream 中文測試";
12 dos.write(line.getBytes());
13 dos.close();
14 }
15 }
範例165:以FileInputStream / DataInputStream、FileOutStream /
DataOutputStream將一個檔案之內容傳遞至另一個檔案內。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
class Ex12_6_3 {
public static void main(String args[])throws Exception {
int i;
if (args.length < 2) {
System.out.println("Usage: java Ex12_6_3 [infileName] [outfileName]");
System.exit(1);
}
String infileName = args[0];
String outfileName = args[1];
FileInputStream fis=new FileInputStream(infileName);
DataInputStream dis = new DataInputStream(fis);
FileOutputStream fos=new FileOutputStream(outfileName);
DataOutputStream dos = new DataOutputStream(fos);
while((i=dis.read()) !=-1) {
dos.write(i);
}
}
}
12-7 FileReader與FileWriter
• 以FileReader / FileWriter 產生之輸入/輸出串流,可讀寫以
雙位元Unicode之輸入/輸出資料,適用亞洲各國文字之編
碼,因此可用於解決中文的問題。
範例166:FileReader之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex12_7_1 {
03 public static void main(String args[]) throws Exception {
04
int i;
05
06
07
08
if (args.length < 1) {
System.out.println("Usage: java Ex12_7_1 [fileName]");
System.exit(1);
}
09
10
11
12
13
14 }
15 }
String fileName = args[0];
FileReader fr=new FileReader(fileName);
while((i=fr.read()) !=-1) {
System.out.print((char)i);
}
範例167:FileWriter之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex12_7_2 {
03 public static void main(String args[]) throws Exception {
04 if (args.length < 1) {
05
System.out.println("Usage: java Ex12_7_2 [fileName]");
06
System.exit(1);
07 }
08
09
String fileName = args[0];
FileWriter fw=new FileWriter(fileName);
10
String line = "Test for FileWriter 測試FileWriter之中文";
11 fw.write(line);
12 fw.flush();
13 }
14 }
範例168:以FileReader / FileWriter將一個檔案之內容傳遞至另一
個檔案內。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex12_7_3 {
03 public static void main(String args[]) throws Exception {
04 int i;
05 if (args.length < 2) {
06
System.out.println("Usage: java Ex12_7_3 [infileName] [outfileName]");
07
System.exit(1);
08 }
09 String infileName = args[0];
10 String outfileName = args[1];
11 FileReader fr=new FileReader(infileName);
12 FileWriter fw=new FileWriter(outfileName);
13 while((i=fr.read()) !=-1) {
14
fw.write(i);
15 }
16 fw.flush();
17 }
18 }
12-8鍵盤資料輸入
• 電腦之週邊設備均可視為是檔案(如鍵盤、螢幕、印表機
等),其間資料的傳遞猶如檔案間資料的傳遞。
範例169:鍵盤資料輸入之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class Ex12_8_1 {
03 public static void main(String [] args)throws IOException {
04 int i;
05
06
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
07 System.out.println("Input data in the keyboard: ");
08 while(true) {
09
i = br.read();
10
System.out.print((char)i);
11 }
12 }
13 }
範例170:由鍵盤輸入資料,以FileOutputStream串流寫入新檔案(無法寫入中文)。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 mport java.io.*;
02 class Ex12_8_2 {
03 public static void main(String [] args)throws IOException {
04 int i;
05
06
07
08
09
if (args.length < 1) {
System.out.println("Usage: java Ex12_8_2 [outfileName]");
System.exit(1);
}
String outfileName = args[0];
10
11
12
13
14
15
16
17
18 }
19 }
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream(outfileName);
System.out.println("Input data in the keyboard: ");
while(true) {
i = br.read();
fos.write(i);
}
範例171:由鍵盤輸入資料,以FileWriter串流寫入新檔案(可寫入中文)。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
class Ex12_8_3 {
public static void main(String [] args)throws IOException {
int i;
if (args.length < 1) {
System.out.println("Usage: java Ex12_8_3 [outfileName]");
System.exit(1);
}
String outfileName = args[0];
InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
FileOutputStream fos = new FileOutputStream(outfileName);
FileWriter fw=new FileWriter(outfileName);
System.out.println("Input data in the keyboard: ");
while((i=br.read()) !=-1) {
fw.write(i);
}
fw.flush();
}
}
第十三章
執行緒(Threads)
13-1 簡介
•
• 作業系統具有多工執行的功能,每一個工作系列即為
一個執行緒(Threads)。在一個時間內,CPU僅能處理
一個工作。當有多個工作同時擁入時,CPU將其本身
分割成多個工作時段,適當地分配給各工作片斷作執
行。也即是當有多個工作同時擁入時,那一個工作的
條件最好,該工作就可先搶到CPU的工作時段,如此
搶CPU的工作時段是謂 執行緒之意義。
13-2執行緒狀態(Thread States)
13-3 Thread類別
• Java系統內建Thread類別,其功能是將CPU分割成多個工作
時段,依前節所述之5個狀態,適當地提供給條件最優的
工作片斷作執行。
範例172:執行緒之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB extends Thread {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例172:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21 public class Ex13_3_1 {
22 public static void main(String[] args) {
23
JOB job1 = new JOB(4,"job1");
24
JOB job2 = new JOB(4,"job2");
25
job1.start();
26
job2.start();
27 }
28 }
範例173:承作Runnable與執行緒之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB implements Runnable {
04 private String jobName;
05 private int loopLmt;
06 public JOB(int loopLmt, String jobName) {
07
this.loopLmt = loopLmt;
08
this.jobName = jobName;
09 }
10 private void PAUSE(double sec) {
11
try {Thread.sleep(Math.round(1000.0*sec));}
12
catch(InterruptedException ie) {};
13 }
範例173:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21
22
23
24
25
26
27
28
public class Ex13_3_2 {
public static void main(String[] args) {
Thread job1 = new Thread(new JOB(4,"job1"));
Thread job2 = new Thread(new JOB(4,"job2"));
job1.start();
job2.start();
}
}
範例174:方法程序isAlive() 與join() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB extends Thread {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例174:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21
22
23
24
25
26
27
28
29
30
31
32
public class Ex13_4_1 {
public static void main(String[] args) {
JOB job1 = new JOB(4,"job1");
JOB job2 = new JOB(8,"job2");
job1.start();
job2.start();
System.out.println("job1 is alive : " +job1.isAlive());
try{job1.join();}
catch(InterruptedException ie){}
System.out.println("job1 is alive : " +job1.isAlive());
}
}
範例175:承作介面Runnable與方法程序isAlive() 、join() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB implements Runnable {
04 private String jobName;
05 private int loopLmt;
06 public JOB(int loopLmt, String jobName) {
07
this.loopLmt = loopLmt;
08
this.jobName = jobName;
09 }
10 private void PAUSE(double sec) {
11
try {Thread.sleep(Math.round(1000.0*sec));}
12
catch(InterruptedException ie) {};
13 }
範例175:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21
22
23
24
25
26
27
28
29
30
31
32
public class Ex13_4_2 {
public static void main(String[] args) {
Thread job1 = new Thread(new JOB(4,"job1"));
Thread job2 = new Thread(new JOB(8,"job2"));
job1.start();
job2.start();
System.out.println("job1 is alive : " +job1.isAlive());
try{job1.join();}
catch(InterruptedException ie){}
System.out.println("job1 is alive : " +job1.isAlive());
}
}
13-5方法程序suspend( )、resume( )
• 執行緒一直是處在搶先機之緊繃環境,但也可以使用方法
程序 suspend( ) 暫時退出此緊張環境,進入等待狀態(如
13-2節之Waiting State),再視需要使用 resume( ) 伺機重新
進入就緒狀態(如13-2節之Ready State),繼續操刀撕殺。
範例176:方法程序suspend() 與resume() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB extends Thread {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例176:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21 public class Ex13_5_1 {
22 public static void main(String[] args) {
23
JOB job1 = new JOB(4,"job1");
24
JOB job2 = new JOB(4,"job2");
25
job1.start();
26
job2.start();
27
job2.suspend();
28
System.out.println("job2 is suspend " );
29
try{job1.join();}
30
catch(InterruptedException ie){}
31
job2.resume();
32
System.out.println("job2 is resume");
33 }
34 }
範例177:承作介面Runnable與方法程序suspend()、resume() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB implements Runnable {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例177:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i);
17
PAUSE(Math.random());
18
}
19 }
20 }
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Ex13_5_2 {
public static void main(String[] args) {
Thread job1 = new Thread(new JOB(4,"job1"));
Thread job2 = new Thread(new JOB(4,"job2"));
job1.start();
job2.start();
job2.suspend();
System.out.println("job2 is suspend " );
try{job1.join();}
catch(InterruptedException ie){}
job2.resume();
System.out.println("job2 is resume");
}
}
13-6方法程序setPriority( )、getPriority( )
• 在眾多執行緒中,必有某些執行緒因須要而必須優先執行,
此時我們可使用方法程序setPriority( ) 設定優先等級,亦可
以getPriority( ) 讀取某執行緒之優先等級。
範例178:方法程序setPriority()、gerPriority() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB extends Thread {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例178:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14
15
16
17
18
19
20 }
21
22
23
24
25
26
27
28
29
30
31
32
33
public void run() {
for(int i=1; i<=loopLmt; i++) {
System.out.println(jobName + ": work" + i +
" priority=: "+getPriority());
PAUSE(Math.random());
}
}
public class Ex13_6_1 {
public static void main(String[] args) {
JOB job1 = new JOB(4,"job1");
JOB job2 = new JOB(4,"job2");
JOB job3 = new JOB(4,"job3");
job1.setPriority(1);
job2.setPriority(3);
job3.setPriority(5);
job1.start();
job2.start();
job3.start();
}
}
範例179:優先等級常數與方法程序setPriority()、gerPriority() 之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.lang.Math.*;
03 class JOB extends Thread {
04 private String jobName;
05 private int loopLmt;
06
07
08
09
public JOB(int loopLmt, String jobName) {
this.loopLmt = loopLmt;
this.jobName = jobName;
}
10
11
12
13
private void PAUSE(double sec) {
try {Thread.sleep(Math.round(1000.0*sec));}
catch(InterruptedException ie) {};
}
範例179:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public void run() {
15
for(int i=1; i<=loopLmt; i++) {
16
System.out.println(jobName + ": work" + i +
" priority=: "+getPriority());
17
PAUSE(Math.random());
18
}
19 }
20 }
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Ex13_6_2 {
public static void main(String[] args) {
JOB job1 = new JOB(4,"job1");
JOB job2 = new JOB(4,"job2");
JOB job3 = new JOB(4,"job3");
job1.setPriority(Thread.MAX_PRIORITY);
job2.setPriority(Thread.NORM_PRIORITY+2);
job3.setPriority(Thread.MIN_PRIORITY);
job1.start();
job2.start();
job3.start();
}
}
13-7 synchronized之應用
• 為了避免這些混亂狀態,我們可籍synchronized 之功能,
令所有執行緒井然有序地進入CPU作執行,在不混亂的狀
況下,迅速執行眾多執行緒之同步工作。在Java語言中,
synchronized是方法程序的修飾子(Modification),可令該方
法程序有 “同步/鎖住” 的功能。允許多個執緒同步進入就
緒狀態,但一個時間僅允許其中一個進入CPU,鎖住其他
執行緒。
範例180:使用修飾子synchronized之應用。(模擬高鐡售票機)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class NumberIssue {
03 int iniNumber, numberInterval;
04 public NumberIssue(int iniNumber, int numberInterval) {
05 this.iniNumber = iniNumber;
06 this.numberInterval = numberInterval;
07 }
08 public synchronized int getNumber()
09 //public int getNumber()
{
10
int num= iniNumber;
11
try {
12
Thread.sleep(1000);
13
} catch (InterruptedException e) {};
範例180:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14
iniNumber= iniNumber + numberInterval;
15
return(num);
16 }
17 }
18 class Passanger extends Thread {
19 int number;
20 NumberIssue NI;
21 public Passanger(NumberIssue NI) {
22 this.NI = NI;
23 }
24 public void run() {
25 number = NI.getNumber();
26 }
27 }
28 public class Ex13_7_1 {
29 public static void main(String[] args) {
30 NumberIssue NI;
31 Passanger p1, p2, p3, p4;
範例180:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
32
NI = new NumberIssue(1,2);
33
34
35
36
p1 = new Passanger(NI);
p2 = new Passanger(NI);
p3 = new Passanger(NI);
p4 = new Passanger(NI);
37
38
39
try {
p1.join(); p2.join(); p3.join(); p4.join();
} catch (InterruptedException e) {};
p1.start();
p2.start();
p3.start();
p4.start();
40 System.out.println("Passanger 1: Number: " + p1.number);
41 System.out.println("Passanger 2: Number: " + p2.number);
42 System.out.println("Passanger 3: Number: " + p3.number);
43 System.out.println("Passanger 4: Number: " + p4.number);
44 }
45 }
範例181:如果不使用修飾子synchronized,當有多個旅客同時購票時,售票機將
售出重號之車票號碼。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class NumberIssue {
03 int iniNumber, numberInterval;
04 public NumberIssue(int iniNumber, int numberInterval) {
05 this.iniNumber = iniNumber;
06 this.numberInterval = numberInterval;
07 }
08 //public synchronized int getNumber()
09 public int getNumber()
{
10
int num= iniNumber;
11
try {
12
Thread.sleep(1000);
13
} catch (InterruptedException e) {};
範例181:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14
iniNumber= iniNumber + numberInterval;
15
return(num);
16 }
17 }
18 class Passanger extends Thread {
19 int number;
20 NumberIssue NI;
21 public Passanger(NumberIssue NI) {
22 this.NI = NI;
23 }
24 public void run() {
25 number = NI.getNumber();
26 }
27 }
28 public class Ex13_7_2 {
29 public static void main(String[] args) {
30 NumberIssue NI;
31 Passanger p1, p2, p3, p4;
範例181:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
32
NI = new NumberIssue(1,2);
33
34
35
36
p1 = new Passanger(NI);
p2 = new Passanger(NI);
p3 = new Passanger(NI);
p4 = new Passanger(NI);
37
38
39
try {
p1.join(); p2.join(); p3.join(); p4.join();
} catch (InterruptedException e) {};
p1.start();
p2.start();
p3.start();
p4.start();
40 System.out.println("Passanger 1: Number: " + p1.number);
41 System.out.println("Passanger 2: Number: " + p2.number);
42 System.out.println("Passanger 3: Number: " + p3.number);
43 System.out.println("Passanger 4: Number: " + p4.number);
44 }
45 }
13-8執行緒群組(Thread Group)之應用
• 為了便於管理,我們可將某些執行緒依需要歸納
成群組,如此編組是謂 “執行緒群組”。
範例182:執行緒群組之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 class JOB extends Thread {
03 int sum;
04 boolean running = true;
05 JOB (ThreadGroup grp, String threadName, int initValue) {
06
super(grp, threadName);
07
this.sum = initValue;
08 }
09 public void run() {
10
while(running)
11
sum = sum + 1;
12 }
13 }
範例182:續1
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
14 public class Ex13_8 {
15 public static void main(String[] args) {
16
ThreadGroup grp1 = new ThreadGroup("grp1");
17
ThreadGroup grp2 = new ThreadGroup("grp2");
18
19
20
21
JOB a1 = new JOB(grp1, "a1", 0);
JOB a2 = new JOB(grp1, "a2", 0);
JOB a3 = new JOB(grp2, "a3", 0);
JOB a4 = new JOB(grp2, "a4", 0);
22
23
24
25
a1.start();
a2.start();
a3.start();
a4.start();
26
27
try {Thread.sleep(1000);}
catch(InterruptedException e){}
範例182:續2
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
28
29
grp1.stop();
grp2.stop();
30
31
32
33
34
35
try {
a1.join();
a2.join();
a3.join();
a4.join();
} catch (InterruptedException e) {};
36
37
38
39
40 }
41 }
System.out.println("grp1_a1: sum = "+a1.sum);
System.out.println("grp1_a2: sum = "+a2.sum);
System.out.println("grp2_a3: sum = "+a3.sum);
System.out.println("grp2_a4: sum = "+a4.sum);
第十四章
網路連通(Network)
14-1 簡介
•
•
•
•
•
•
Java語言有許多其他語言所不能及的優點,除了物件導向之優資技術之外,
網路資料串流又是其中最大優點之一,不需要如其他語言大張旗鼓地先架設
網路平台網站,然後執行網路資料傳遞,Java只需於程式中增寫幾列程式碼
即可執行網路資料傳遞。
本章設計Server/Client網路程式,解釋最基礎之網路連接,設計Client端網路
程式,連接Server端。Server端以設定之執行埠(port) 建置伺服網站平台
(ServerSocket),當Client端有訊息來連接時,以連接平台(Socket) 之接收功能
接受連接,並捉取Client端的網址(IP) 印出之。Client端以Server之網址(IP)、
及設定之執行埠(port) 建立網路連接平台,由Client端連接Server端。
有關Java網路程式之設計,筆者將詳細解述於本系列叢書第二冊,內容將包
括網路連接、網路連接記錄、網路訊息傳遞、網路檔案傳遞、網路對播、網
路群播、網路動畫設計、線上對陣、線上弈棋、線上對陣等內容。
14-2網路程式
• Java網路應用,不必大費周章地架設網站,只須簡短幾行
程式碼即可搞定。本節將設計Server / Client 端點網路程式
並實作網路連接。先以Server端建立網站平台,等待Client
端來連接;再以Client端尋找Server端要求網路連接;當完
成網路連接後,Server端捕捉Client端之IP。
範例183:Server網站平台之建立,並捕捉Client端之IP。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.net.*;
02 import java.io.*;
03 public class Server14 {
04 ServerSocket SS;
05 Socket socket;
06 static int port;
07 public Server14( ) {
08 try{
09
SS = new ServerSocket(port);
10
System.out.println("Server created.");
11
System.out.println("waiting for client to connect...");
範例183:續
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
12
13
socket = SS.accept();
System.out.println("connected from Client " +
socket.getInetAddress().getHostAddress());
socket.close();
14
15
}
16
catch(IOException e){
17
System.out.println(e.toString());
18
e.printStackTrace();
19
System.exit(1);
20
}
21 }
22 public static void main(String args[]){
23
if(args.length < 1){
24
System.out.println("Usage: java Server14 [port]");
25
System.exit(1);
26
}
27
port=Integer.parseInt(args[0]);
28
Server14 ServerStart=new Server14();
29 }
30 }
範例184:Client連接Server端之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.net.*;
03 public class Client14 {
04 Socket socket;
05 static String servername;
06 static int port;
07 public Client14() {
08 try{
09
socket=new Socket(InetAddress.getByName(servername),port);
10
socket.close();
11
}
12
catch(IOException e){
13
System.out.println("IOException when connecting Server!");
14
}
15 }
範例184:續
•
•
•
•
•
•
•
•
•
•
16 public static void main(String args[]) {
17
if (args.length < 2){
18
System.out.println("USAGE: java Client14 [servername] [port]");
19
System.exit(1);
20
}
21
servername= args[0];
22
port=Integer.parseInt(args[1]);
23
Client14 ClientStart=new Client14();
24 }
25 }
第十五章
常用類別之應用
15-1 簡介
•
• 於前述各章,我們已探討Java之各類觀念問題,本章將介
紹Java常用的內建類別。依筆者了解常用的內建類別至少
有350則,限於篇幅,在此僅就一般程式設計與SCJP考題
常用之類別作基礎實用的解說,讀者可由本篇更熟練(1)建
構子、(2)類別方法程序、(3)實體方法程序之應用,進而類
推至其他類別之應用。並可參與Java作業手冊之使用。
15-2 Math Class
• java.lang.Math繼承自Object,此類別猶如小型函數庫,包
括常用之數學函式與常數E、PL,此類別無建構子,無需
產生新物件實體化,直接呼叫函式即可執行。
範例185:類別Math與常數之應用。
•
•
•
•
•
•
•
01 class Ex15_2_1 {
02 public static void main(String args[]) {
03
System.out.println("E = " + Math.E);
04
System.out.println("PI = " + Math.PI);
05 }
06 }
例186:類別Math與類別方法程序三角函數之應用。
•
•
•
•
•
•
01 class Ex15_2_2 {
02 public static void main(String args[]) {
03
System.out.println ("atan(1) = " + Math.atan(1));
04 }
05 }
例187:類別Math與類別方法程序概數之應用。
•
•
•
•
•
•
•
01 class Ex15_2_3 {
02 public static void main(String args[]) {
03
System.out.println("round(2.49) = " + Math.round(2.49));
04
System.out.println("round(2.5) = " + Math.round(2.5));
05 }
06 }
15-3 Byte Class
• java.lang.Byte繼承自Object,此類別是對應基本資料型態
byte之類別,包括常用之byte方法程序與常數MIN_VALUE、
MAX_VALUE。有關類別Short、Long、Float、Long之內容,
可參考本節之解述。
例188:類別Byte與常數之應用。
•
•
•
•
•
•
•
01 class Ex15_3_1 {
02 public static void main(String args[]) {
03
System.out.println("MIN_VALUE = " + Byte.MIN_VALUE);
04
System.out.println("MAX_VALUE = " + Byte.MAX_VALUE);
05 }
06 }
例189:類別Byte與類別方法程序之應用。
•
• class Ex15_3_2 {
•
public static void main(String args[]) {
•
System.out.println("parseByte() = " + Byte.parseByte("123"));
•
System.out.println("decode() = " + Byte.decode("123"));
•
}
• }
例190:類別Byte與實體比較方法程序之應用。
•
•
•
•
•
•
•
•
•
01 class Ex15_3_3 {
02 public static void main(String args[]) {
03
byte a = 2, b =4;
04
Byte bb = new Byte(a);
05
System.out.print("compare from a to b = " +
bb.compareTo(b));
06 }
07 }
例191:類別Byte與實體覆蓋方法程序之應用。
• class Ex15_3_4 {
•
public static void main(String args[]) {
•
byte a = 2;
•
Byte bb = new Byte(a);
•
System.out.println("byteValue = " + bb.byteValue());
•
System.out.println("floatValue = " + bb.floatValue());
•
System.out.println("doubleValue = " + bb.doubleValue());
•
System.out.println("intValue = " + bb.intValue());
•
System.out.println("longValue = " + bb.longValue());
•
}
• }
15-4 Integer Class
• java.lang.Integer繼承自Object,此類別是對應基本
資料型態int之類別,包括常用之int方法程序與常
數MIN_VALUE、MAX_VALUE。
例192:類別Integer與常數之應用。
•
• class Ex15_4_1 {
•
public static void main(String args[]) {
•
System.out.println("MIN_VALUE = " + Integer.MIN_VALUE);
•
System.out.println("MAX_VALUE = " + Integer.MAX_VALUE);
• }
• }
例193:類別Integer與類別方法程序之應用。
•
• class Ex15_4_2 {
•
public static void main(String args[]) {
•
System.out.println("parseInt() = " + Integer.parseInt("123"));
•
System.out.println("valueOf() = " + Integer.valueOf("123"));
•
}
• }
例194:類別Integer與特定型態字串解析之應用。
•
• class Ex15_4_3 {
•
public static void main(String args[]) {
•
System.out.println("toBinaryString() = " +
•
Integer.toBinaryString(10));
•
System.out.println("toHexString() = " + Integer.toHexString(10));
•
System.out.println("toOctalString() = " +
•
Integer.toOctalString(10));
•
System.out.println("toString() = " + Integer.toString(10));
•
System.out.println("toString() = " + Integer.toString(10, 2));
•
}
• }
例195:類別Integer與實體方法程序之應用。
•
• class Ex15_4_4 {
•
public static void main(String args[]) {
•
int a = 2;
•
Integer bb = new Integer(a);
•
System.out.println("floatValue = " + bb.floatValue());
•
System.out.println("doubleValue = " +
•
bb.doubleValue());
•
System.out.println("intValue = " + bb.intValue());
•
System.out.println("longValue = " + bb.longValue());
•
}
• }
15-5 Character Class
• java.lang.Character繼承自Object,此類別是對應基本資料
型態char之類別,包括常用之char方法程序與常數
MIN_VALUE、MAX_VALUE。
例196:類別Character與常數之應用。
•
•
•
•
•
•
•
class Ex15_5_1 {
public static void main(String args[]) {
System.out.println("MIN_VALUE = " + Character.MIN_VALUE);
System.out.println("MAX_VALUE = " + Character.MAX_VALUE);
}
}
例197:類別Character與char/Unicode 轉換類別方法程序之應用。
•
•
•
•
•
•
•
•
•
class Ex15_5_2 {
public static void main(String args[]) {
System.out.println("digit('a', 16) = " + Character.digit('a', 16));
System.out.println("digit('b', 16) = " + Character.digit('b', 16));
System.out.println("forDigit(10, 16) = " + Character.forDigit(10, 16));
System.out.println("forDigit(11, 16) = " + Character.forDigit(11, 16));
}
}
例198:類別Character與測試類別方法程序之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
class Ex15_5_3 {
public static void main(String args[]) {
System.out.println("isDefined('a')
= " + Character.isDefined('a'));
System.out.println("isDigit('a')
= " + Character.isDigit('a'));
System.out.println("isJavaLetter('a') = " + Character.isJavaLetter('a'));
System.out.println("isLetter('a')
= " + Character.isLetter('a'));
System.out.println("isLetterOrDigit('a') = " + Character.isLetterOrDigit('a'));
System.out.println("isLowerCase('a') = " + Character.isLowerCase('a'));
System.out.println("isUpperCase('a') = " + Character.isUpperCase('a'));
System.out.println("isSpace('a')
= " + Character.isSpace('a'));
}
}
例199:類別Character與實體方法程序之應用
•
• class Ex15_5_4 {
•
public static void main(String args[]) {
•
Character ch = new Character('a');
•
System.out.println("charValue() = " + ch.charValue());
• }
• }
15-6 Boolean Class
• java.lang.Boolean繼承自Object,此類別是對應基本資料型
態boolean之類別,使用TRUE/FALSE常數或boolean值
true/false。
例200:類別Boolean與常數之應用。
•
• class Ex15_6_1 {
•
public static void main(String args[]) {
•
Boolean b1 = new Boolean(true);
•
Boolean b2 = Boolean.TRUE;
•
boolean b3 = Boolean.TRUE;
•
•
System.out.println("b1 = " + b1);
•
System.out.println("b2 = " + b2);
•
System.out.println("b3 = " + b3);
•
}
• }
例201:類別Boolean與類別方法程序之應用。
•
•
•
•
•
•
•
•
•
class Ex15_6_2 {
public static void main(String args[]) {
System.out.println("valueOf(\"true\") = " + Boolean.valueOf("true"));
System.out.println("valueOf(\"TRUE\") = " + Boolean.valueOf("TRUE"));
System.out.println("valueOf(\"false\") = " + Boolean.valueOf("false"));
System.out.println("valueOf(\"abcd\") = " + Boolean.valueOf("abcd"));
}
}
例202:類別Boolean與實體方法程序之應用。
•
• class Ex15_6_3 {
•
public static void main(String args[]) {
•
Boolean b = new Boolean(true);
•
System.out.println("booleanValue() = " + b.booleanValue());
•
}
• }
15-7 String Class
• java.lang.String繼承自Object,此類別是對應基本資料型態
String之類別,此資料型態與其他變數型態不同,一旦建
立後,即被視為是一個物件,不得再被改變。
•
• String是唯一擁有屬於自己的運算元之類別,“+” 連接兩組
字串,例:s1 = “abcd”、s2 = “xyz”,則a1+a2 = “abcdxyz”。
例203:類別String與複製char矩陣類別方法程序之應用。
•
• class Ex15_7_1 {
•
public static void main(String args[]) {
•
char[] s = {'a', 'b', 'c', 'd'};
•
System.out.println("(s[]) = " + String.copyValueOf(s));
•
System.out.println("(s[], 1, 3) = " + String.copyValueOf(s, 1, 3));
•
}
• }
例204:類別String與String物件解析類別方法程序之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
class Ex15_7_2 {
public static void main(String args[]) {
boolean b = true;
char c = 'c';
char[] data = {'a', 'b', 'c', 'd'};
double d = 1234.56;
float f = 123.45f;
int i = 1234;
long l = 12345L;
System.out.println("boolean = " + String.valueOf(b));
System.out.println("char = " + String.valueOf(c));
System.out.println("data[] = " + String.valueOf(data));
System.out.println("data[] = " + String.valueOf(data, 2, 2));
System.out.println("double = " + String.valueOf(d));
System.out.println("float = " + String.valueOf(f));
System.out.println("int = " + String.valueOf(i));
System.out.println("long = " + String.valueOf(l));
}
}
例205:類別String與實體比較方法程序之應用。
•
• class Ex15_7_3 {
•
public static void main(String args[]) {
•
String s1 = "abcd", s2 ="xyz";
•
String str = new String(s1);
•
System.out.print("compare from s1 to s2 = " + str.compareTo(s2));
•
}
• }
例206:類別String與實體長度方法程序之應用。
•
• class Ex15_7_4 {
•
public static void main(String args[]) {
•
String s = "abcd";
•
String str = new String(s);
•
System.out.print("length = " + str.length());
• }
• }
例207:類別String與實體取代方法程序之應用。
•
• class Ex15_7_5 {
•
public static void main(String args[]) {
•
String s = "abcabcabc";
•
String str = new String(s);
•
System.out.print("replace = " + str.replace('a', 'x'));
• }
• }
例208:類別String與實體子字串方法程序之應用。
•
• class Ex15_7_6 {
•
public static void main(String args[]) {
•
String s = "abcdefghijk";
•
String str = new String(s);
•
System.out.println(“substring(3) = ” + str.substring(3));
•
System.out.println("substring(3, 6) = " + str.substring(3, 6));
•
}
• }
例209:類別String與實體連接方法程序之應用。
•
• class Ex15_7_7 {
•
public static void main(String args[]) {
•
String s1 = "abcd";
•
•
String str = new String(s1);
•
System.out.println("concat() = " + str.concat("xyz"));
•
System.out.println("concat() = " + str.concat("123"));
•
}
• }
15-8 StringBuffer Class
• java.lang.StringBuffer繼承自Object,類別StringBuffer與類別
String類似,不同之處是前者可作內部修改。
例210:類別StringBuffer與實體連接方法程序之應用。
•
• class Ex15_8_1 {
•
public static void main(String args[]) {
•
String s = "abcd";
•
•
StringBuffer str = new StringBuffer(s);
•
System.out.println(“boolean = ” + str.append(true));
•
System.out.println(“char = ” + str.append(‘x’));
•
System.out.println(“double = ” + str.append(111.1d));
•
System.out.println(“int = ” + str.append(222));
•
System.out.println("String = " + str.append("xyz"));
•
}
• }
例211:類別StringBuffer與實體插入方法程序之應用。
•
• class Ex15_8_2 {
•
public static void main(String args[]) {
•
String s = "abcd";
•
•
StringBuffer str = new StringBuffer(s);
•
System.out.println("boolean = " + str.insert(2, true));
•
System.out.println(“char = ” + str.insert(2, ‘x’));
•
System.out.println(“double = ” + str.insert(2, 111.1d));
•
System.out.println(“int = ” + str.insert(2, 222));
•
System.out.println("String = " + str.insert(2, "xyz"));
•
}
• }
例212:類別StringBuffer與實體讀取容量方法程序之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class Ex15_8_3 {
02 public static void main(String args[]) {
03
04
StringBuffer str1 = new StringBuffer(5);
System.out.println("str1 capacity = " + str1.capacity());
05
06
StringBuffer str2 = new StringBuffer("");
System.out.println("str2 capacity = " + str2.capacity());
07
StringBuffer str3 = new StringBuffer("abcd");
08
System.out.println("str3 capacity = " + str3.capacity());
09 }
10 }
例213:類別StringBuffer與實體讀取長度方法程序之應用。
•
• class Ex15_8_4 {
•
public static void main(String args[]) {
•
•
StringBuffer str = new StringBuffer("abcd");
•
System.out.println("str capacity = " + str.capacity());
•
System.out.println("str length = " + str.length());
• }
• }
例214:類別StringBuffer與實體字串反轉方法程序之應用。
•
• class Ex15_8_5 {
•
public static void main(String args[]) {
•
String s = "abcdxyz";
•
•
StringBuffer str = new StringBuffer(s);
•
System.out.println("str reverse = " + str.reverse());
• }
• }
15-9 Object Class
• java.lang.Object是唯一不作繼承的類別,是Java所
有其他類別之祖先類別,在此所定義的方法程序,
也是其他類別之共同方法程序。
例215:類別Object與物件比較之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 class sample {
02 int a, b, c;
03 sample(int x, int y, int z) {
04
a = x; b= y; c = z;
05 }
06 }
07 class Ex15_9_1 {
08 public static void main(String args[]) {
09
sample samp1 = new sample(1, 2, 3);
10
sample samp2 = new sample(1, 2, 3);
11
System.out.println("samp1==samp2 : " + (samp1==samp2));
12
System.out.println("samp1.equals(samp2) : " + samp1.equals(samp2));
13
sample samp3 = samp1;
14
System.out.println("samp1==samp3 : " + (samp1==samp3));
15
System.out.println("samp1.equals(samp3) : " + samp1.equals(samp3));
16 }
17 }
例216:類別Object與變數比較之應用。
•
• class Ex15_9_2 {
•
public static void main(String args[]) {
•
int a = 2, b = 2;
•
•
System.out.println("(a == b) : " + (a == b));
•
•
Integer A = new Integer(a);
•
Integer B = new Integer(b);
•
System.out.println("A.equals(B) : " + A.equals(B));
•
}
• }
15-10 File Class
• java.io.File繼承自Object,此類別為檔案物件之原
始型態,以其建立檔案新物件,執行檔案之各項
功能,java.io.* 不是預設包裹(java.lang.*),編輯程
式時必需寫入import java.io.* 執行匯入。
例217:類別File與類別變數之應用。
•
•
•
•
•
•
•
•
•
•
•
import java.io.*;
class Ex15_10_1 {
public static void main(String args[]) {
System.out.println("pathSeparator = " + File.pathSeparator);
System.out.println("pathSeparatorChar = " + File.pathSeparatorChar);
System.out.println("separator = " + File.separator);
System.out.println("separatorChar = " + File.separatorChar);
}
}
例218:類別File與實體測試方法程序之應用。
•
• import java.io.*;
•
• class Ex15_10_2 {
•
public static void main(String args[]) {
•
File f = new File(".", "Ex15_10_2.java");
•
•
System.out.println("exists = " + f.exists());
•
System.out.println("isDirectory = " + f.isDirectory());
•
System.out.println("isFile = " + f.isFile());
•
System.out.println("canRead = " + f.canRead());
•
System.out.println("canWrite = " + f.canWrite());
•
}
• }
例219:類別File與實體資料方法程序之應用。
•
• import java.io.*;
•
• class Ex15_6_3 {
•
public static void main(String args[]) {
•
File f = new File(".", "Ex15_10_3.java");
•
•
System.out.println("getAbsolutePath = " + f.getAbsolutePath());
•
System.out.println("getNam = " + f.getName());
•
System.out.println("getParent = " + f.getParent());
•
System.out.println("getPath = " + f.getPath());
•
}
• }
例220:類別File與實體應用方法程序之應用。
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
01 import java.io.*;
02 import java.util.*;
03 class Ex15_10_4 {
04 public static void main(String args[]) {
05
File f = new File(".", "Ex15_10_4.java");
06
System.out.println("lastModified Second = " + f.lastModified());
07
System.out.println("length = " + f.length());
08
09
10
11
12
13
14 }
15 }
Date d = new Date(f.lastModified());
System.out.println("lastModified Year = " + (d.getYear()+1900));
System.out.println("lastModified Month = " + d.getMonth());
System.out.println("lastModified Date = " + d.getDate());
System.out.println("lastModified Hours = " + d.getHours());
System.out.println("lastModified Minutes = " + d.getMinutes());
15-11 Date Class
• java.util.Date繼承自Object,以年、月、日、時、分、秒組
成之Date物件,以millisecond為計時單位,java.util.* 不是
預設包裹(java.lang.*),編輯程式時必需寫入import
java.util.* 執行匯入。
例221:類別Date與類別方法程序之應用。
•
•
•
•
•
•
•
•
•
•
•
01 import java.util.*;
02 class Ex15_11_1 {
03 public static void main(String args[]) {
04
System.out.println("parse = " +
Date.parse("Fri, 3 Aug 2007 22:15:00"));
05
System.out.println("UTC = " +
Date.UTC(107, 7, 3, 22, 15, 0 ));
06 }
07 }
例222:類別Date與實體讀取時間方法程序之應用。
•
• import java.util.*;
•
• class Ex15_11_2 {
•
public static void main(String args[]) {
•
Date d = new Date();
•
•
System.out.println("Year = " + (d.getYear() + 1900));
•
System.out.println("Month = " + d.getMonth());
•
System.out.println("Date = " + d.getDate());
•
System.out.println("Day = " + d.getDay());
•
System.out.println("Hours = " + d.getHours());
•
System.out.println("Minutes = " + d.getMinutes());
•
System.out.println("Seconds = " + d.getSeconds());
•
}
• }
例223:類別Date與實體GMT時間方法程序之應用。
•
• import java.util.*;
•
• class Ex15_11_3 {
•
public static void main(String args[]) {
•
Date d = new Date();
•
•
System.out.println("TimezoneOffset = " +
•
d.getTimezoneOffset());
•
System.out.println("toGMTString = " + d.toGMTString());
•
System.out.println("toLocaleString = " + d.toLocaleString());
•
}
• }