第一篇:java實(shí)驗(yàn) 報(bào)告(寫寫幫整理)
專業(yè)選修課程實(shí)驗(yàn)(1)實(shí)驗(yàn)報(bào)告
課程名稱____ JAVA程序設(shè)計(jì) 學(xué)生學(xué)院__ 計(jì)算機(jī)學(xué)院______ 專業(yè)班級___ 12計(jì)科6班 學(xué) 號____ 3112006006 學(xué)生姓名____ 黃新健 指導(dǎo)教師______ 黃劍鋒
2014 年 12 月 16 日
實(shí)驗(yàn)一:Java語言綜述
一、實(shí)驗(yàn)?zāi)康呐c要求
1、熟悉安裝和配置JDK開發(fā)環(huán)境。
2、熟悉安裝和配置IDE開發(fā)工具。
3、掌握J(rèn)ava程序編輯、編譯和運(yùn)行的過程。
4、掌握J(rèn)ava程序的構(gòu)成特點(diǎn)。
5、總結(jié)在調(diào)試過程中的錯誤。
二、實(shí)驗(yàn)類型
驗(yàn)證型
三、實(shí)驗(yàn)原理及說明
通過實(shí)際操作,使學(xué)生對Java語言的使用有一個更深刻的理解;熟悉Java的開發(fā)環(huán)境及程序結(jié)構(gòu)。
四、實(shí)驗(yàn)儀器
安裝JDK及Java IDE的計(jì)算機(jī)若干臺
五、實(shí)驗(yàn)內(nèi)容和步驟
1、下載、安裝并設(shè)置 Java SDK 軟件包。
2、安裝 Java IDE軟件。
3、編寫一個簡單的 Java 程序,運(yùn)行結(jié)果為在屏幕上輸出“HELLO WORLD!”。public class Hello{ public static void main(String args[]){ System.out.println(“HELLO WORLD!”);} }
心得:該程序主要是讓我們懂得怎么樣編寫一個簡單java程序,使我們在日后的程序過程中對java編程有基本的認(rèn)識和了解。
六、注意事項(xiàng)
Java源程序文件的命名規(guī)則。
七、預(yù)習(xí)與思考題
1、什么是Java虛擬機(jī)?它的作用是什么? 答:含義:Java虛擬機(jī)是一個想象中的機(jī)器,在實(shí)際的計(jì)算機(jī)上通過軟件模擬來實(shí)現(xiàn)。Java虛擬機(jī)有自己想象中的硬件,如處理器、堆棧、寄存器等,還具有相應(yīng)的指令系統(tǒng)。
作用:生成在Java虛擬機(jī)上運(yùn)行的目標(biāo)代碼(字節(jié)碼),可以在多種平臺上不加修改地運(yùn)行。Java虛擬機(jī)在執(zhí)行字節(jié)碼時(shí),能把字節(jié)碼解釋成具體平臺上的機(jī)器指令執(zhí)行。
2、如何在不同的環(huán)境下設(shè)置環(huán)境變量?
答:用鼠標(biāo)右擊“我的電腦”->屬性->高級->環(huán)境變量系統(tǒng)變量->新建->變量名:JAVA_HOME 變量值:JDK安裝的路徑
系統(tǒng)變量->編輯->變量名:Path 在變量值的最前面加上:%JAVA_HOME%bin;(若已經(jīng)有Path項(xiàng),無須另外新建,直接在后面加,但需用;與前面已有的項(xiàng)分隔開)
系統(tǒng)變量->新建->變量名:CLASSPATH 變量值:.;%JAVA_HOME%lib;%JAVA_HOME%libdt.jar;%JAVA_HOME%libtools.jar;最后測試下環(huán)境變量是否設(shè)置成功
3、Java Application和Java Applet的不同之處?
答:運(yùn)行方式不同、運(yùn)行工具不同、程序結(jié)構(gòu)不同、受到的限制不同
實(shí)驗(yàn)二:Java語言基礎(chǔ)
一、實(shí)驗(yàn)?zāi)康呐c要求
1、掌握 Java 基本數(shù)據(jù)類型、運(yùn)算符與表達(dá)式、數(shù)組和字符串的使用方法。
2、掌握各種變量的聲明方式。
3、理解 Java 程序語法結(jié)構(gòu),掌握順序結(jié)構(gòu)、選擇結(jié)構(gòu)和循環(huán)結(jié)構(gòu)語法的程序設(shè)計(jì)方法。
4、通過以上內(nèi)容,掌握 Java 語言的編程規(guī)則。
5、了解Java程序文件名和類名的說明方法。
二、實(shí)驗(yàn)類型
設(shè)計(jì)型
三、實(shí)驗(yàn)原理及說明 Java語言基礎(chǔ)包括數(shù)據(jù)類型、運(yùn)算符、表達(dá)式、流程控制、數(shù)組、字符串等,是類內(nèi)方法設(shè)計(jì)實(shí)現(xiàn)的基礎(chǔ)。面向?qū)ο蟪绦蛟O(shè)計(jì)的核心是類和類內(nèi)方法的設(shè)計(jì),其中類內(nèi)方法的設(shè)計(jì)依然需要傳統(tǒng)的面向過程的方法進(jìn)行。
四、實(shí)驗(yàn)儀器
安裝JDK及Java IDE的計(jì)算機(jī)若干臺
五、實(shí)驗(yàn)內(nèi)容和步驟
1、編寫聲明不同數(shù)據(jù)類型變量的程序文件 Java2_1.java,源代碼如下: public class Java2_1{ public static void main(String args[]){ byte b=0x55;short s=0x55ff;int i=1000000;long l=0xffffL;char c='a';float f=0.23F;double d=0.7E-3;boolean B=true;String S=“這是字符串類數(shù)據(jù)類型”;System.out.println(“字節(jié)型變量 b = ”+b);System.out.println(“短整型變量 s = ”+s);System.out.println(“整型變量 i = ”+i);System.out.println(“長整型變量 l = ”+l);System.out.println(“字符型變量 c = ”+c);System.out.println(“浮點(diǎn)型變量 f = ”+f);System.out.println(“雙精度變量 d = ”+d);System.out.println(“布爾型變量 B = ”+B);System.out.println(“字符串類對象 S = ”+S);} } 編譯并運(yùn)行該程序。
心得:主要讓我們了解到不同數(shù)據(jù)的類型及他們定義的方式,通過運(yùn)行結(jié)果截圖讓我對不同的數(shù)據(jù)類型有了更明顯的認(rèn)識。
2、建立 Java2_2.java 文件,通過本程序了解變量的使用范圍,源代碼如下。
public class Java2_2{ static int i=10;public static void main(String args[]){ { int k=10;System.out.println(“i=”+i);System.out.println(“k=”+k);} System.out.println(“i=”+i);System.out.println(“k=”+k);//編譯時(shí)將出錯,已出k的使用范圍 } } 結(jié)果:運(yùn)行時(shí)出現(xiàn)錯,編譯不成功。
編譯 Java2_2.java,此時(shí)會出現(xiàn)錯誤提示。因?yàn)樽兞?k 在方法塊中聲明,在方法塊之外它是不存在的,所以編譯時(shí)會出錯。
修改上面的程序,并成功運(yùn)行該程序。
public class Java2_2.java { static int i=10;static int k=10;public static void main(String args[]){ {
System.out.println(“i=”+i);System.out.println(“k=”+k);} System.out.println(“i=”+i);System.out.println(“k=”+k);} }
分析:因定義的k只有在其方法塊了內(nèi)可以使用,而在其方法塊之外是不可能使用,經(jīng)過修改,我把變量k定義到了main函數(shù)上面,這樣在任意的方法塊內(nèi)都可以使用k這個變量。
3、運(yùn)行下面的程序,理解String類常用方法的使用。public class 2_4{ public static void main(String args[]){ String str=”I like java programming”;int i1=str.indexOf(‘j’);String s1=str.substring(i1);String s2=str.substring(i1,i1+4);int i2=str.lastIndexOf(‘j’);String s3=str.substring(i2+5);System.out.println(“s1=”+s1);System.out.println(“s2=”+s2);System.out.println(“s3=”+s3);} }
心得: 通過運(yùn)行以及參考運(yùn)行結(jié)果,讓我對String類常用方法有了進(jìn)一步了解,也讓我學(xué)習(xí)到更多String類方法。
4、(選做)編程采用冒泡法實(shí)現(xiàn)對數(shù)組元素由小到大排序,冒泡法排序?qū)ο噜彽膬蓚€元素進(jìn)行比較,并把小的元素交換到前面。class MySort {
public static void main(String[] args){
MySort sort = new MySort();
int[] arr = new int[]{1,22,101,5,250,99,20,22,50};
sort.sort(arr);
for(int i : arr){
System.out.print(i+“,”);
}
}
public void sort(int[] a){
int temp = 0;
for(int i = 0;i for(int j = i;j if(a[i]>a[j]){ temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } } 分析:該程序主要用的算法是冒泡法,通過冒泡法把定義好的數(shù)組的元素按小到大輸出,其實(shí)涉及的內(nèi)容還是很基本的,過程沒花費(fèi)很多時(shí)間。 5、(選做)數(shù)組實(shí)驗(yàn):利用數(shù)組解決約瑟夫環(huán)問題。設(shè)有n個人圍做一圈并按順時(shí)針方向從1到n編號,從第s個人開始進(jìn)行1到m報(bào)數(shù),報(bào)數(shù)到第m的人出圈,再從其下一個人重新開始從1到m的報(bào)數(shù),如此進(jìn)行下去知道所有的人都出圈為止。給出這n個人出圈的順序。import java.util.Scanner;class yue{ public static void main(String[] args){ } } System.out.println(“請輸入人數(shù):”);Scanner sca=new Scanner(System.in);int m=sca.nextInt();System.out.println(“請輸入從第幾個人報(bào)數(shù)::”);int s=sca.nextInt();int[] a=new int[m];int length=m;for(int i=0;i if(j%m==0){ System.out.print(a[i%m]+“"); a[i%m]=-1; j=1; i++; length--; } else{ j++; i++;} } else{ i++;} } 體會:該程序比較靈活,可以任意輸入人數(shù)、從第幾個人開始報(bào)數(shù)。這里沒用隊(duì)列知識,而是直接利用數(shù)組得到出圈人順序。主要思想通過循環(huán)把數(shù)到規(guī)定數(shù)字的人的值設(shè)為-1并輸出(表示出圈),在下次循環(huán)中只要判斷各個數(shù)組的值是否大于0,是的話則判斷是否數(shù)到規(guī)定數(shù)字。否則跳過該元素,判斷下一個數(shù)。 Java語言中的數(shù)組與C語言中的數(shù)組差別。 七、預(yù)習(xí)與思考題 1、定義變量的作用是什么? 答:確定變量的作用域,按作用域的不同,變量可以分為成員變量、局部變量和方法的參數(shù)。 2、&和&&有什么區(qū)別? 答:&是位與,一般用于取字節(jié)位數(shù),不管怎樣都會執(zhí)行&兩邊的程序。&&是且,一般用于判斷語句的雙重條件,只有&&左邊為TRUE才會執(zhí)行右邊的程序。 3、break和continue在流程控制中的作用是什么? 答:具體循環(huán)中break的作用是終止執(zhí)行下面語句并跳出循環(huán)。 而continue作用是跳過下面語句進(jìn)行下一次循環(huán)。 實(shí)驗(yàn)三:面向?qū)ο缶幊?/p> 一、實(shí)驗(yàn)?zāi)康呐c要求 1、理解 Java 語言是如何體現(xiàn)面向?qū)ο缶幊袒舅枷搿?/p> 2、了解類的封裝方法,以及如何創(chuàng)建類和對象。 3、掌握成員變量和成員方法的特性及構(gòu)造方法使用。 4、熟練掌握 OOP 方式進(jìn)行程序設(shè)計(jì)的方法,理解類的繼承性和多態(tài)性的作用。 二、實(shí)驗(yàn)類型 設(shè)計(jì)型 三、實(shí)驗(yàn)原理及說明 Java語言中引入了類,因此在程序設(shè)計(jì)中可以把數(shù)據(jù)及對數(shù)據(jù)的操作封裝在一起;類可以從其他類中繼承數(shù)據(jù)和方法。 四、實(shí)驗(yàn)儀器 安裝JDK及Java IDE的計(jì)算機(jī)若干臺 五、實(shí)驗(yàn)內(nèi)容和步驟 1、定義一個“圓”類Circle,該圓類的數(shù)據(jù)成員包括:圓心點(diǎn)位置及圓的半徑;方 法成員有:設(shè)置圓心位置和半徑的方法,獲取圓心位置和半徑的方法及構(gòu)造方法。要求構(gòu)造方法可以接收圓心位置參數(shù),而半徑使用缺省值1。編寫完整的程序并 創(chuàng)建Circle類的對象,并且分別調(diào)用各種方法,對比這些方法的執(zhí)行結(jié)果,并據(jù) 此寫出詳細(xì)的實(shí)驗(yàn)報(bào)告。class Circle{ double x,y,r; //x,y分別表示圓心橫縱坐標(biāo) void Setmid(double a,double b){ x=a; y=b; return;} void Sethalf(double rr){ r=rr;return;} void Getmid(){ System.out.println(”x=“+ x); System.out.println(”y=“+ y);} double Gethalf(){ return r;} public static void main(String args[]){ Circle c=new Circle(); c.Setmid(5.0,6.0);//設(shè)圓心位置 c.Sethalf(1.0); //設(shè)半徑長度 c.Getmid(); //獲取圓心位置 System.out.println(”半徑=“+c.Gethalf());//獲取半徑長度 } } 分析:主要是考察關(guān)于創(chuàng)建類、方法以及調(diào)用的類中方法的知識。創(chuàng)建編寫出的圓類并給其中方法設(shè)置初始值x=5.0,y=6.0,半徑=1.0,運(yùn)行程序即可得到上述圖片的結(jié)果。本程序不足之處就是不可以任意輸入圓心坐標(biāo)以及半徑。 2、定義以上圓類Circle的子類SubCircle,使它具有獲取半徑方法、設(shè)置半徑方 法和構(gòu)造方法,要求構(gòu)造方法可同時(shí)接收圓心位置及半徑兩個參數(shù)。編寫完整的 程序并創(chuàng)建SubCircle類的對象,并且分別調(diào)用各種方法,對比這些方法的執(zhí)行 結(jié)果,并據(jù)此寫出詳細(xì)的實(shí)驗(yàn)報(bào)告。實(shí)驗(yàn)代碼: class Circle{ double x,y,r; //x,y分別表示圓心橫縱坐標(biāo) void Setmid(double a,double b){ x=a; y=b; return;} void Sethalf(double rr){ r=rr;return;} void Getmid(){ System.out.println(”x=“+ x); System.out.println(”y=“+ y);} void Gethalf(){ System.out.println(”半徑=“+ r);} } class SubCircle extends Circle{ void Getmnh(){ //同時(shí)獲取遠(yuǎn)點(diǎn)和半徑構(gòu)造方法 Getmid(); Gethalf();} public static void main(String args[]){ SubCircle c=new SubCircle(); c.Setmid(5.0,6.0);//設(shè)圓心位置 c.Sethalf(1.0); //設(shè)半徑長度 c.Getmnh(); //同時(shí)獲取圓心位置和半徑長度 } } 結(jié)果截圖: 體會:本實(shí)驗(yàn)跟上述實(shí)驗(yàn)有些不同,另外寫了一個類,聲明一種方法Getmnh()同時(shí)獲取遠(yuǎn)點(diǎn)和半徑構(gòu)造方法。然而該實(shí)驗(yàn)不足之處也是不可任意輸入圓心及半徑的數(shù)據(jù)。 3、(選做)多態(tài)在工資系統(tǒng)中的應(yīng)用。下面給出一個根據(jù)雇員類型利用多態(tài)性完成工資單計(jì)算的程序。定義一個類Employee作為超類,Employee的子類有Boss(每星期發(fā)給他固定工資,而不計(jì)工作時(shí)間)、PieceWorker(按其生產(chǎn)的產(chǎn)品數(shù)發(fā)放工資)、HourlyWorker(根據(jù)工作時(shí)間長短發(fā)放工資)。對所有雇員類型都使用earnings()方法完成其工資單的計(jì)算,但每個人掙的工資按他所屬的雇員類計(jì)算,所有雇員類都是從超類Employee派出生的。所以在超類中聲明earnings()方法,該方法沒有實(shí)質(zhì)性工作,而是在每個子類都提供恰當(dāng)?shù)膃arnings()方法的重寫。為了計(jì)算雇員的工資,程序僅使用雇員對象的一個超類引導(dǎo)并調(diào)用earnings()方法。 //Employee超類的定義 class Employee{ private String firstName;private String lastName;public Employee(String first,String last){ firstName=first;lastName=last;} public String getEmployeeName(){ return firstName;} public String getLastName(){ return lastName;} public String toStrings(){ return firstName+' '+lastName;} public double earnings(){ System.out.println(”Employ's salary is 0.0“);return 0.0;} } //定義Boss類,為Employee的子類 class Boss extends Employee{ private double weeklySalary;public Boss(String first,String last,double s){ super(first,last);setWeeklySalary(s);} public void setWeeklySalary(double s){ weeklySalary=(s>0?s:0);} public double earnings(){ return weeklySalary;} public String toStrings(){ return ”Boss: “+super.toStrings();} } //定義PieceWorker類,為Employee的子類 class PieceWorker extends Employee{ private double wagePiece;private int quantity;public PieceWorker(String first,String last,double w,int q){ super(first,last);setWage(w);setQuantity(q);} public void setWage(double w){ wagePiece=(w>0?w:0);} public void setQuantity(int q){ quantity=(q>0?q:0);} public double earnings(){ return quantity*wagePiece;} public String toStrings(){ return ”PieceWoeker: “+super.toStrings();} } //定義HourlyWorker類,為Employee的子類 class HourlyWorker extends Employee{ private double wage;private double hours;public HourlyWorker(String first,String last ,double w,double h){ super(first,last);setWage(w);setHours(h);} public void setWage(double w){ wage=(w>0?w:0);} public void setHours(double h){ hours=(h>=0&&h<168?h:0);} public double earnings(){ return wage*hours;} public String toStrings(){ return ”HourlyWorker: “+super.toStrings();} } Public class TestEmployee{ public static void main(String args[ ]){ //使用超類聲明ref Employee ref;String out=”“;//分別定義各子類 Boss b=new Boss(”Hohn“,”Smith“,800.00);PieceWorker p=new PieceWorker(”Bob“,”Lewis“,2.5,200);HourlyWorker h=new HourlyWorker(”Karen“,”price“,13.75,40);//使用子類分別實(shí)例化 ref=b;out+=ref.toStrings()+” earned $“+ref.earnings()+”n“+b.toStrings()+ ” earned $“+b.earnings()+”n“;System.out.print(out);ref=p;out+=ref.toStrings()+” earned $“+ref.earnings()+”n“+p.toStrings()+ ” earned $“+p.earnings()+”n“;System.out.print(out);ref=h;out+=ref.toStrings()+” earned $“+ref.earnings()+”n“+h.toStrings()+ ” earned $“+h.earnings()+”n“;System.out.print(out);} } 分析:設(shè)計(jì)思路主要是根據(jù)工種的不同而創(chuàng)建不同的結(jié)算工資類去繼承員工類,這樣是問題變得更加簡單而且結(jié)構(gòu)性強(qiáng),不同的類有不同的工資算法,這樣就不會造成混淆,也利于添加其他的結(jié)算工資類和維護(hù)。 六、注意事項(xiàng) 子構(gòu)造方法的使用。 七、預(yù)習(xí)與思考題 1、如何繼承一個類? 答:使用extends關(guān)鍵字即可繼承一個類。 2、為什么說構(gòu)造函數(shù)是一種特殊的方法?特殊在哪里?構(gòu)造函數(shù)什么時(shí)候執(zhí)行?被誰調(diào)用? 答:因?yàn)闃?gòu)造函數(shù)沒有函數(shù)返回值也不能被定義為void;構(gòu)造函數(shù)名與類名相同;一旦定義好一個構(gòu)造函數(shù),創(chuàng)建對象時(shí)就會自動調(diào)用它;被系統(tǒng)調(diào)用。 3、同名的不同方法共存的情況稱為什么?如何區(qū)分這些同名方法? 答:重載。根據(jù)參數(shù)的個數(shù)或者參數(shù)的類型的不同可以區(qū)分同名方法。 實(shí)驗(yàn)四:Java類和對象的高級特征 一、實(shí)驗(yàn)?zāi)康呐c要求 1、掌握接口的編寫及使用。 2、理解抽象類與最終類。 3、掌握包的編寫以及如何使用包中的類。 二、實(shí)驗(yàn)類型 設(shè)計(jì)型 三、實(shí)驗(yàn)原理及說明 接口借助于類來實(shí)現(xiàn),Java語言利用接口來實(shí)現(xiàn)多態(tài)性;Java包的機(jī)制。 四、實(shí)驗(yàn)儀器 安裝JDK及Java IDE的計(jì)算機(jī)若干臺 五、實(shí)驗(yàn)內(nèi)容和步驟 1、接口的編寫 ⑴ 編寫一個接口myInterface。interface myInterface{ int i=4;int k=5;void myFunc1();int myFunc2(int x);} ⑵ 編寫一個用于實(shí)現(xiàn)接口myInterface的類UseInterface。class UseInterface implements Interfaceclass{ int j;public void myFunc1(){ //在使用接口的類中一定要實(shí)現(xiàn)接口中的所有抽象方法 System.out.println(“myFunc1=”+1);} public int myFunc2(int i){ System.out.println(“func2=”+1);return i;} public static void main(String srgs[]){ UseInterface x = new UseInterface();x.myFunc1();x.myFunc2(k);} } 心得::主要涉及到創(chuàng)建一個接口和繼承接口所有抽象方法的知識內(nèi)容,讓我對接口的概念以及用法有了進(jìn)一步了解。 2、抽象類和最終類的使用 ⑴ 定義一個抽象類Shape用于描述圖形,具有“名稱”(name)屬性以及計(jì)算其面積和周長的兩個抽象方法GetArea()和GetLength()。定義一個最終類Circle繼承自類Shape,增加了一個描述半徑的屬性radius及帶參的構(gòu)造函數(shù)用于該類對象的初始化操作,同時(shí)實(shí)現(xiàn)了Shape類中的兩個抽象方法來計(jì)算圓的面積和周長。定義一個最終類Rectangle繼承自類Shape,增加了兩個屬性length和width用于描述矩形的長和寬及帶參的構(gòu)造函數(shù)用于完成對該類對象的初始化,同時(shí)實(shí)現(xiàn)了Shape類中的兩個抽象方法來計(jì)算矩形的面積和周長。package lei; public abstract class Shape { String name;void GetArea(){ } void GetLength(){ } } class Circle extends Shape{ double radius;Circle(double r){ radius=r;} double GetArea(double radius){ double s; s=3.14*radius*radius; return s; } double GetLength(double radius){ double l; l=3.14*2*radius; return l;} void Getanl(){ System.out.println(”圓的面積=“+GetArea(radius)); System.out.println(”圓的周長=“+GetLength(radius));} } class Rectangle extends Shape{ double width,length;Rectangle(double w,double l){ width=w; length=l;} double GetArea(double width,double length){ double s; s=width*length; return s; } double GetLength(double width,double length){ double l; l=2*(width+length); return l;} void GetAnl(){ System.out.println(”矩形的面積=“+GetArea(width,length)); System.out.println(”矩形的周長=“+GetLength(width,length));} public static void main(String args[]){ Rectangle r=new Rectangle(3.0,4.0); Circle c=new Circle(1.0); c.Getanl(); r.GetAnl();} } 分析:寫了一個主抽象類和幾個抽象方法,并寫了一個圓類、一個矩形類分別去繼承抽象類,并重新定義了其中的方法。這兩個類中都用到了構(gòu)造方法,并對抽象中g(shù)etarea()、getlength()方法重新定義。 ⑵(選做)重寫上面的程序,要求將Circle類和Rectangle類放到不同的包中,用包的技術(shù)組織程序的設(shè)計(jì)。同時(shí)要求程序能從鍵盤上接受數(shù)據(jù)以便求解不同的幾何圖形的周長面積。 package circle; import java.util.Scanner; public abstract class Circleclass { String name;void GetArea(){ } void GetLength(){ } } class Circle extends Circleclass{ double radius;Circle(double r){ radius=r;} double GetArea(double radius){ double s; s=3.14*radius*radius; return s; } double GetLength(double radius){ double l; l=3.14*2*radius; return l;} void Getanl(){ System.out.println(”圓的面積=“+GetArea(radius)); System.out.println(”圓的周長=“+GetLength(radius));} public static void main(String args[]){ Scanner radius=new Scanner(System.in); } } System.out.println(”請輸入圓的半徑“);int r=radius.nextInt();Circle c=new Circle(r);c.Getanl(); package rectangle; import java.util.Scanner; public abstract class Rectangleclass { String name;void GetArea(){ } void GetLength(){ } } class Rectangle extends Rectangleclass{ double width,length;Rectangle(double w,double l){ width=w; length=l;} double GetArea(double width,double length){ double s; s=width*length; return s; } double GetLength(double width,double length){ double l; l=2*(width+length); return l;} void GetAnl(){ System.out.println(”矩形的面積=“+GetArea(width,length)); System.out.println(”矩形的周長=“+GetLength(width,length));} public static void main(String args[]){ Scanner l=new Scanner(System.in); System.out.println(”請輸入矩形的長和寬“); int c=l.nextInt(); int k=l.nextInt(); Rectangle r=new Rectangle(c,k); r.GetAnl();} } 六、注意事項(xiàng) 一個類用于實(shí)現(xiàn)某個接口的話則必須實(shí)現(xiàn)該接口中的所有方法。 七、預(yù)習(xí)與思考題 1、內(nèi)部類inner class和外部類的區(qū)別? 答:內(nèi)部類可以使用包涵類里面的成員變量,和包含類的成員方法是并列的。其他的外部類不能用內(nèi)部類創(chuàng)建對象,只有在包涵類里面創(chuàng)建內(nèi)部類對象。 2、抽象類和接口的區(qū)別? 答:抽象類里面可以有非抽象方法,抽象類不能被實(shí)例化,但是可以被繼承,繼承抽象類必須要實(shí)現(xiàn)所有的抽象方法,抽象方法不能有方法體。 而接口里只能有抽象方法,沒有一個有程序體。接口只可以定義static final成員變量。接口變量可以引用具體實(shí)現(xiàn)類的實(shí)例。接口只能被實(shí)現(xiàn)(繼承),一個具體類實(shí)現(xiàn)接口,必須使用全部的 抽象方法。接口之間可以繼承。一個具體類可以實(shí)現(xiàn)多個接口,實(shí)現(xiàn)多繼承現(xiàn)象。 實(shí)驗(yàn)五:圖形用戶界面的設(shè)計(jì) 一、實(shí)驗(yàn)?zāi)康呐c要求 掌握GUI編程中的主要概念:AWT,Swing,窗口、面板,容器布局,布局管理器。掌握GUI編程。掌握事件編程機(jī)制。 二、實(shí)驗(yàn)類型 設(shè)計(jì)型 三、實(shí)驗(yàn)原理及說明 圖形用戶界面是應(yīng)用程序與用戶交流的圖形接口,由各種不同的組件按照一定的布局模式排列組成的,如菜單、按鈕、標(biāo)簽等,與這些組件配合工作的還有一些相關(guān)的事件。 四、實(shí)驗(yàn)儀器 安裝JDK及Java IDE的計(jì)算機(jī)若干臺 五、實(shí)驗(yàn)內(nèi)容和步驟 1、編程包含一個標(biāo)簽和一個按鈕,單擊按鈕時(shí),標(biāo)簽的內(nèi)容在”你好“和”再見“之間切換。 package change;import java.awt.*;import java.awt.event.*;import java.applet.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JFrame;public class changetext { public static void main(String args[]){ ApplicationFrame AF = new ApplicationFrame(); } } class ApplicationFrame extends JFrame implements ActionListener { Label prompt;Button btn;ApplicationFrame(){ super(”我的窗口“); prompt = new Label(”你好“); btn = new Button(”顯示“); setLayout(new FlowLayout()); add(prompt); add(btn); btn.addActionListener(this); setVisible(true); setSize(500, 600); setLocation(300, 400); } public void actionPerformed(ActionEvent e){ if(e.getActionCommand()== ”顯示“){ if(prompt.getText().equals(”你好“)) prompt.setText(”再見“); else if(prompt.getText().equals(”再見“)) prompt.setText(”你好“); } } } 分析:主要考察的是頁面布局和事件處理方面的知識,通過點(diǎn)擊按鈕產(chǎn)生事件改變標(biāo)簽中內(nèi)容,給按鈕加個事件監(jiān)聽,再寫一個事件處理方法即可。 2、編程包含一個單選按鈕組和一個普通按鈕,單選按鈕組中包含三個單選,文本說明分別為“普通”、“黑體”和“斜體”。選擇文本標(biāo)簽為“普通”的單選按鈕時(shí),普通按鈕中的文字為普通字體,選擇文本標(biāo)簽為“黑體”的單選按鈕時(shí),普通按鈕中的文字的字體為黑體,選擇文本標(biāo)簽為“斜體”的單選按鈕時(shí),普通按鈕中的文字的字體為斜體。import java.awt.*;import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class click implements ActionListener{ JRadioButton b1,b2,b3;JButton b4;click(){ JFrame frame=new JFrame(); JPanel panel=new JPanel(); ButtonGroup group=new ButtonGroup(); frame.setLayout(new FlowLayout());frame.getContentPane().add(panel);b1=new JRadioButton(”普通“);b2=new JRadioButton(”黑體“);b3=new JRadioButton(”斜體“);b4=new JButton(”普通按鈕“); panel.add(b1); panel.add(b2); panel.add(b3); panel.add(b4); group.add(b1); group.add(b2); group.add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); frame.pack(); frame.setVisible(true);} public void actionPerformed(ActionEvent e){ if(e.getActionCommand()==”普通“){ b4.setFont(new Font(”普通“,Font.PLAIN,14)); } if(e.getActionCommand()==”黑體“){ b4.setFont(new Font(”黑體“,Font.BOLD,14)); } if(e.getActionCommand()==”斜體“){ b4.setFont(new Font(”斜體“,Font.ITALIC,14)); } } public static void main(String[] args){ click c=new click();} } 分析:主要考察的是單選按鈕組和普通按鈕知識,通過選擇不同的單選按鈕,是普通按鈕中內(nèi)容發(fā)生改變,其中還涉及到設(shè)置字體字型、大小的知識。 3、(選做)編程確定當(dāng)前鼠標(biāo)的位置坐標(biāo)。import java.awt.Point;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.JFrame;/** */ public class location extends JFrame implements MouseListener{ public location(){ this.setSize(500, 400); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.addMouseListener(this); this.setVisible(true); } public void mouseClicked(MouseEvent e){ //點(diǎn)擊時(shí)產(chǎn)生事件 Point p = e.getPoint();//獲得坐標(biāo) this.setTitle(”當(dāng)前坐標(biāo):“ + p.x + ”,“ + p.y);} public void mousePressed(MouseEvent e){ } public void mouseReleased(MouseEvent e){ } public void mouseEntered(MouseEvent e){ } public void mouseExited(MouseEvent e){ } public static void main(String[] args){ location loc=new location();} } 分析:用到mouselistener、mouseclicked,通過點(diǎn)擊鼠標(biāo)左鍵即可獲得鼠標(biāo)所在位置的坐標(biāo)。 4、(選做)編程使用BorderLayout布局方式放置5個按鈕。import javax.swing.*;import java.awt.event.*;import java.awt.*; public class gettext extends JFrame { public static final int DEFAULT_WIDTH = 300;public static final int DEFAULT_HEIGHT = 300; public gettext(){ setTitle(”BORDER布局“);setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);JButton e= new JButton(”東“);JButton s= new JButton(”南“);JButton w= new JButton(”西“);JButton n= new JButton(”北“);JButton m= new JButton(”中“);getContentPane().add(n, BorderLayout.NORTH);getContentPane().add(m, BorderLayout.CENTER);getContentPane().add(s, BorderLayout.SOUTH);getContentPane().add(e, BorderLayout.EAST);getContentPane().add(w, BorderLayout.WEST);pack();setVisible(true);} public static void main(String[] args){ gettext a=new gettext(); } } 分析:運(yùn)用到borderlayout布局方式對5個按鈕進(jìn)行東西南北中方向的布局,總體來看還是比較簡單的。 六、注意事項(xiàng) 通過接口來完成事件處理時(shí),應(yīng)實(shí)現(xiàn)接口中的所有方法。 七、預(yù)習(xí)與思考題 1、Java的事件處理機(jī)制是怎樣? 答:三個概念:事件源、事件和監(jiān)聽器。當(dāng)事件源產(chǎn)生事件時(shí),通過調(diào)用事件監(jiān)聽器相應(yīng)的事件處理方法。 事件處理機(jī)制: 1、事件處理器。 2、事件監(jiān)聽器接口與事件監(jiān)聽器類。事件監(jiān)聽器實(shí)現(xiàn)方式分為自身類作為事件監(jiān)聽器、外部類作為事件監(jiān)聽器、匿名類作為事件監(jiān)聽器和內(nèi)部類作為事件監(jiān)聽器4種。 3、注冊事件監(jiān)聽器。 一個組件可以注冊一個或多個監(jiān)聽器對象,事件對象只向已注冊的監(jiān)聽器 對象報(bào)告事件發(fā)生 2、若一個數(shù)據(jù)只有兩種取值可能,采用哪種組件表示比較合適?如果有二種到三種取值可能,采用哪種合適?如果取值的可能大于5個,采用哪種組件合適? 答:如果是兩到三種取值且相互排斥,采用單選按鈕比較合適,否則采用復(fù)選按鈕。如果是5種以上的取值且只能選一,則用choice下拉列表,否則用list下拉列表。 實(shí)驗(yàn)六:Java Applet的編寫 一、實(shí)驗(yàn)?zāi)康呐c要求 1、掌握J(rèn)ava Applet程序結(jié)構(gòu)和開發(fā)過程。 2、了解Applet運(yùn)行機(jī)制。 3、學(xué)會編寫Applet對應(yīng)的HTML文件,掌握從HTML文件向Applet傳遞參數(shù)的方法。 4、了解Applet與瀏覽器的通信。 5、掌握Applet圖形界面設(shè)計(jì)。 二、實(shí)驗(yàn)類型 設(shè)計(jì)型 三、實(shí)驗(yàn)原理及說明 學(xué)習(xí)編輯、編譯、運(yùn)行Applet程序的方法。在Applet程序中沒有實(shí)現(xiàn)main()方法,這是Applet與應(yīng)用程序Application的區(qū)別之一。由于Applet中沒有main()方法作為Java解釋器的入口,所以必須編寫HTML文件,把該Applet嵌入其中,然后用appletviewer來運(yùn)行,或在支持Java的瀏覽器上運(yùn)行,如IE。通過程序的運(yùn)行掌握Applet的生命周期。 四、實(shí)驗(yàn)儀器 安裝JDK及Java IDE的計(jì)算機(jī)若干臺 五、實(shí)驗(yàn)內(nèi)容和步驟 1、Applet程序的生命周期。 import java.awt.*;import java.applet.*;public class AppLife extends Applet{ static int a,b,c,d;int x1=150,y1=50,x2=300,y2=50;public void paint(Graphics g){ g.drawLine(x1,y1,x1,y2);//x1->x2 g.drawLine(x1,y1,x1,y1+a);g.drawString(”init“,x1,y1);g.drawLine(x1+50,y1,x1+50,y1+b);g.drawString(”start“,x1+50,y1);g.drawLine(x1+100,y1,x1+100,y1+c);g.drawString(”stop“,x1+100,y1);g.drawLine(x1+150,y1,x1+150,y1+d);g.drawString(”destory“,x2,y2);} public void init(){ a+=50;repaint();} public void start(){ b+=50;repaint();} public void stop(){ } } 分析: Applet的生命周期中有四個狀態(tài):初始態(tài)、運(yùn)行態(tài)、停止態(tài)和消亡態(tài)。當(dāng)程序執(zhí)行完init()方法以后,Applet程序就進(jìn)入了初始態(tài),然后馬上執(zhí)行start()方法。而沒有執(zhí)行stop(),destory().2、(選做)編寫一個小應(yīng)用程序,由HTML文件向其傳遞參數(shù)。要求把HTML文件中設(shè)置的兩組數(shù)據(jù)(“Susan”,85)和(“Jeff”,96)傳遞給Applet并在瀏覽器中顯示。主類class文件: package te;import java.applet.*;import java.awt.*;public class gettext extends Applet { int s;int x;public void init(){ s=Integer.parseInt(getParameter(”Susan“)); x=Integer.parseInt(getParameter(”Jeff“)); System.out.println(”susan:“+s); System.out.println(”jeff:“+x); } } Html程序文件: 心得:由于瀏覽器版本的問題和對該類知識不熟,實(shí)驗(yàn)過程一直出現(xiàn)問題,經(jīng)過不斷尋找資料,不斷的調(diào)試對問題有了進(jìn)一步的了解,也給我了學(xué)習(xí)新知識的機(jī)會。 六、注意事項(xiàng) Applet的生命周期。 七、預(yù)習(xí)與思考題 1、構(gòu)造方法、start()方法和init()方法誰先被執(zhí)行? 答:構(gòu)造方法先被執(zhí)行,然后構(gòu)造方法調(diào)用init()方法,最后系統(tǒng)會執(zhí)行start()方法。 2、Applet如何與網(wǎng)頁中其他對象通信? 答:使用getApplet和getApplets這兩個方法,Applet能夠?qū)ふ业狡渌腁pplet并調(diào)用它們的方法,就可以實(shí)現(xiàn)Applet與網(wǎng)頁對象通信。 《Java簡易聊天室》 實(shí)驗(yàn)?zāi)康模簩?shí)現(xiàn)簡單的客服端與服務(wù)端通訊,進(jìn)一步鞏固,加深對Java語言基礎(chǔ)知識的了解,將理論與實(shí)際相結(jié)合。 實(shí)驗(yàn)要求:能相互之間發(fā)送消息,并進(jìn)行簡單的異常處理。 聊天室截圖與說明: 客戶端 服務(wù)端 將客服端與服務(wù)端程序同時(shí)運(yùn)行,此時(shí)會顯示出客戶端與服務(wù)端界面。在客戶端界面上點(diǎn)擊“連接”按鈕,即可使客戶端與服務(wù)端進(jìn)程建立連接。在文本框中輸入將要發(fā)送的消息,點(diǎn)擊“發(fā)送”按鈕,即可將消息發(fā)送到對應(yīng)端口。當(dāng)服務(wù)端發(fā)送消息時(shí),服務(wù)端便相當(dāng)于客戶端。當(dāng)需要終止連接時(shí),關(guān)閉相應(yīng)窗口即可。 設(shè)計(jì)概要:類/接口/函數(shù)說明 1.public class ClientUI extends Jframe{} public class ServerUI extends Jframe{} ClientUI與ServerUi繼承Frame類構(gòu)建客戶端與服務(wù)器端窗口。 2.class ChatClient extends Thread{} class SvrCom extends Thread{} 通訊類ChatClient/SvrCom負(fù)責(zé)守候數(shù)據(jù)到來 3.public void run() 用于監(jiān)聽客戶端/服務(wù)器端發(fā)送來的信息,運(yùn)行連接 4.public void sendMsg(String msg){// 用于發(fā)送信息 try { out.println(“【客戶端】” + msg); } catch(Exception e){ System.out.println(e); } } public void sendMsg(String msg){// 用于發(fā)送信息 try { out.println(“【服務(wù)器】” + msg);// 把信息寫入輸出流 } catch(Exception e){ System.out.println(e); } } 5.try { msg = in.readLine();// 從in對象上讀數(shù)據(jù)信息 } catch(SocketException ex){ System.out.println(ex); break; } catch(Exception ex){ System.out.println(ex); } if(msg!= null && msg.trim()!= “"){ System.out.println(”>>“ + msg); ui.mainArea.append(msg + ”n“); } 簡單的異常處理 6.public ChatClient(String ip, int port, ClientUI ui){// 初始化ChatClient類 this.ui = ui; try { sc = new Socket(ip, port);// 創(chuàng)建sc, 用服務(wù)器ip和端口作參數(shù) System.out.println(”已順利聯(lián)接到服務(wù)器。“); out = new PrintWriter(sc.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(sc.getInputStream())); } catch(Exception e){ System.out.println(e); } start(); public SvrCom(ServerUI ui){ // 初始化SvrCom類 this.ui = ui; ui.setServer(this); try { soc = new ServerSocket(6666);// 開設(shè)服務(wù)器端口6666 System.out.println(”啟動服務(wù)器成功,等待端口號:6666“); client = soc.accept();// 當(dāng)客戶機(jī)請求連接時(shí),創(chuàng)建一條鏈接 System.out.println(”連接成功!來自“ + client.toString()); in = new BufferedReader(new InputStreamReader(client .getInputStream())); out = new PrintWriter(client.getOutputStream(), true); } catch(Exception ex){ System.out.println(ex); } start(); 自我評價(jià)或總結(jié):經(jīng)過本次實(shí)驗(yàn),進(jìn)一步了解了客戶端與服務(wù)器之間的通信機(jī)制,對以后的編程實(shí)踐墊定了基礎(chǔ)。同時(shí)還鞏固了GUI圖形界面知識,更重要的是它使我對網(wǎng)絡(luò)編程有了一定的了解,也學(xué)到了不少知識。 附: 源代碼:import java.io.*;import java.net.*;import javax.swing.*;import java.awt.event.*;import java.awt.*; public class ClientUI extends JFrame { JTextArea mainArea; JTextArea sendArea; ChatClient client;JTextField ipArea;JButton btnLink;public void setClient(ChatClient client){ this.client = client;} public ClientUI(){ super(”客戶端“);Container contain = getContentPane();contain.setLayout(new BorderLayout());mainArea = new JTextArea();JScrollPane mainAreaP = new JScrollPane(mainArea);JPanel panel = new JPanel();panel.setLayout(new BorderLayout());sendArea = new JTextArea(3, 8);JButton sendBtn = new JButton(”發(fā)送“);sendBtn.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ client.sendMsg(sendArea.getText()); mainArea.append(”【客戶端】“ + sendArea.getText()+ ”n“); sendArea.setText(”“); } });JPanel ipPanel = new JPanel();ipPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));ipPanel.add(new JLabel(”服務(wù)器:“));ipArea = new JTextField(12);ipArea.setText(”127.0.0.1“);ipPanel.add(ipArea);btnLink = new JButton(”連接“);ipPanel.add(btnLink);btnLink.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ client = new ChatClient(ipArea.getText(), 6666, ClientUI.this); ClientUI.this.setClient(client); } }); panel.add(sendBtn, BorderLayout.EAST); panel.add(sendArea, BorderLayout.CENTER); contain.add(ipPanel, BorderLayout.NORTH); contain.add(mainAreaP, BorderLayout.CENTER); contain.add(panel, BorderLayout.SOUTH); setSize(500, 300); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);} public static void main(String[] args){ ClientUI ui = new ClientUI();} } class ChatClient extends Thread { Socket sc;BufferedReader in;PrintWriter out;ClientUI ui; public ChatClient(String ip, int port, ClientUI ui){ this.ui = ui; try { sc = new Socket(ip, port); System.out.println(”已順利聯(lián)接到服務(wù)器。“); out = new PrintWriter(sc.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(sc.getInputStream())); } catch(Exception e){ System.out.println(e); } start();} public void run(){ String msg = ”“; while(true){ try { msg = in.readLine(); } catch(SocketException ex){ System.out.println(ex); break; } catch(Exception ex){ System.out.println(ex); } if(msg!= null && msg.trim()!= ”“){ System.out.println(”>>“ + msg); ui.mainArea.append(msg + ”n“); } } } public void sendMsg(String msg){ try { out.println(”【客戶端】“ + msg); } catch(Exception e){ System.out.println(e); } } } import java.io.*;import java.net.*;import javax.swing.*;import java.awt.event.*;import java.awt.*;/** * 服務(wù)端界面ServerUI */ public class ServerUI extends JFrame { JTextArea mainArea; JTextArea sendArea; JTextField indexArea; SvrCom server; public void setServer(SvrCom server){ this.server = server;} public ServerUI(){ super(”服務(wù)器端“); Container contain = getContentPane(); contain.setLayout(new BorderLayout()); mainArea = new JTextArea(); JScrollPane mainAreaP = new JScrollPane(mainArea);JPanel panel = new JPanel();panel.setLayout(new BorderLayout());sendArea = new JTextArea(3, 8);JButton sendBtn = new JButton(”發(fā)送“);sendBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae){ server.sendMsg(sendArea.getText()); mainArea.append(”【服務(wù)器】sendArea.getText()+ “n”); sendArea.setText(“"); } });JPanel tmpPanel = new JPanel();indexArea = new JTextField(2);indexArea.setText(”0“);tmpPanel.add(sendBtn);tmpPanel.add(indexArea);panel.add(tmpPanel, BorderLayout.EAST);panel.add(sendArea, BorderLayout.CENTER);contain.add(mainAreaP, BorderLayout.CENTER);contain.add(panel, BorderLayout.SOUTH);setSize(500, 300);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);} public static void main(String[] args){ ServerUI ui = new ServerUI();SvrCom server = new SvrCom(ui);} } class SvrCom extends Thread { Socket client;ServerSocket soc;BufferedReader in;PrintWriter out;ServerUI ui;// ChatServer server;public SvrCom(ServerUI ui){ ” + this.ui = ui;ui.setServer(this);try { soc = new ServerSocket(6666); } System.out.println(“啟動服務(wù)器成功,等待端口號:6666”); client = soc.accept(); System.out.println(“連接成功!來自” + client.toString()); in = new BufferedReader(new InputStreamReader(client .getInputStream())); out = new PrintWriter(client.getOutputStream(), true);} catch(Exception ex){ System.out.println(ex);} start();} public void run(){ String msg = “";while(true){ try { msg = in.readLine(); } catch(SocketException ex){ System.out.println(ex); break; } catch(Exception ex){ System.out.println(ex); } if(msg!= null && msg.trim()!= ”“){ System.out.println(”>>“ + msg); ui.mainArea.append(msg + ”n“); } } } public void sendMsg(String msg){ try { out.println(”【服務(wù)器】" + msg);} catch(Exception e){ System.out.println(e);} } 學(xué) 生 實(shí) 驗(yàn) 報(bào) 告 冊 (理工類) 課程名稱:面向?qū)ο蟪绦蛟O(shè)計(jì) 專業(yè)班級:16計(jì)算機(jī)科學(xué)與技術(shù)(專轉(zhuǎn)本) 學(xué)生學(xué)號: 1613203022 學(xué)生姓名: 張義丹 所屬院部: 計(jì)算機(jī)工程 指導(dǎo)教師: 劉 晶 16 ——20 17 學(xué)年 第 2 學(xué)期 金陵科技學(xué)院教務(wù)處制 實(shí)驗(yàn)報(bào)告書寫要求 實(shí)驗(yàn)報(bào)告上交電子稿,標(biāo)題采用四號黑體,正文采用小四號宋體,單倍行距。 實(shí)驗(yàn)報(bào)告書寫說明 實(shí)驗(yàn)報(bào)告中實(shí)驗(yàn)?zāi)康暮鸵?、?shí)驗(yàn)儀器和設(shè)備、實(shí)驗(yàn)內(nèi)容與過程、實(shí)驗(yàn)結(jié)果與分析這四項(xiàng)內(nèi)容為必需項(xiàng)。教師可根據(jù)學(xué)科特點(diǎn)和實(shí)驗(yàn)具體要求增加項(xiàng)目。 填寫注意事項(xiàng) (1)細(xì)致觀察,及時(shí)、準(zhǔn)確、如實(shí)記錄。(2)準(zhǔn)確說明,層次清晰。 (3)盡量采用專用術(shù)語來說明事物。 (4)外文、符號、公式要準(zhǔn)確,應(yīng)使用統(tǒng)一規(guī)定的名詞和符號。(5)應(yīng)獨(dú)立完成實(shí)驗(yàn)報(bào)告的書寫,嚴(yán)禁抄襲、復(fù)印,一經(jīng)發(fā)現(xiàn),以零分論處。 實(shí)驗(yàn)報(bào)告批改說明 實(shí)驗(yàn)報(bào)告的批改要及時(shí)、認(rèn)真、仔細(xì),一律用紅色筆批改。實(shí)驗(yàn)報(bào)告的批改成績采用五級記分制或百分制,按《金陵科技學(xué)院課堂教學(xué)實(shí)施細(xì)則》中作業(yè)批閱成績評定要求執(zhí)行。 實(shí)驗(yàn)項(xiàng)目名稱:Java編程基礎(chǔ) 實(shí)驗(yàn)學(xué)時(shí): 6 同組學(xué)生姓名: ———— 實(shí)驗(yàn)地點(diǎn): 工科樓A101 實(shí)驗(yàn)日期: 17.3.21~17.4.4 實(shí)驗(yàn)成績: 批改教師: 劉晶 批改時(shí)間: 實(shí)驗(yàn)1 Java編程基礎(chǔ) 一、實(shí)驗(yàn)?zāi)康暮鸵?/p> (1)熟練掌握J(rèn)DK1.6及Eclipse4.2編寫調(diào)試Java應(yīng)用程序及Java小程序的方法;(2)熟練掌握J(rèn)ava應(yīng)用程序的結(jié)構(gòu); (3)了解Java語言的特點(diǎn),基本語句、運(yùn)算符及表達(dá)式的使用方法;(4)熟練掌握常見數(shù)據(jù)類型的使用; (5)熟練掌握if-else、switch、while、do-while、for、continue、break、return語句的使用方法; (6)熟練掌握數(shù)組和字符串的使用; (7)調(diào)試程序要記錄調(diào)試過程中出現(xiàn)的問題及解決辦法; (8)編寫程序要規(guī)范、正確,上機(jī)調(diào)試過程和結(jié)果要有記錄,不斷積累編程及調(diào)試經(jīng)驗(yàn); (9)做完實(shí)驗(yàn)后給出本實(shí)驗(yàn)的實(shí)驗(yàn)報(bào)告。 二、實(shí)驗(yàn)儀器和設(shè)備 奔騰以上計(jì)算機(jī),Windows 操作系統(tǒng),裝有JDK1.6和Eclipse4.2軟件。 三、實(shí)驗(yàn)過程 (1)分別使用JDK命令行和Eclipse編譯運(yùn)行Java應(yīng)用程序;適當(dāng)添加注釋信息,通過javadoc生成注釋文檔;為主方法傳遞參數(shù)“Hello world”字符串,并輸出,記錄操作過程。 public class Hello { public static void main(String args[]){ System.out.println(“Hello!”);} }(2)分別使用JDK命令行和Eclipse編譯Java Applet,并建立HTML文檔運(yùn)行該Applet。壓縮生成“.jar”文件。記錄操作過程。import java.awt.*;import java.applet.Applet;public class HelloApplet extends Applet { public void paint(Graphics g){ g.setColor(Color.red);g.drawString(“Hello!”,20,20);} } (3)根據(jù)變量score中存放的考試分?jǐn)?shù),輸出對應(yīng)的等級。要求從鍵盤輸入學(xué)生成績,60分以下為D等;60~69為C等;70~89為B等;90~100為A等。(4)編寫一個Java Application程序,輸出區(qū)間[200,300]上的所有素?cái)?shù),將其用數(shù)組prime[]保存,并以每10個一行的形式顯示運(yùn)行結(jié)果。(5)輸出下列數(shù)字形式,要求用二維數(shù)組完成。①n=4 0 0 0 0 0 1 1 1 0 1 2 2 0 1 2 3 ② n=4 1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1(6)求二維數(shù)組的鞍點(diǎn),即該位置上的元素在該行上最大,在列上最小。也可能無鞍點(diǎn)。(7)分析下列程序的輸出結(jié)果,掌握equals()方法和“= =”的區(qū)別。class StringTest2{ public static void main(String args[]){ String s1 = “This is the second string.”; String s2 = “This is the second string.”; String s3 = new String(“This is the second string.”); String s4 = new String(s1); String s5 = s1; boolean result121 = s1.equals(s2); boolean result122 = s1 == s2; boolean result131 = s1.equals(s3); boolean result132 = s1 == s3; boolean result141 = s1.equals(s4); boolean result142 = s1 == s4; boolean result151 = s1.equals(s5); boolean result152 = s1 == s5; System.out.println(“s1 equals s2= ” +result121); System.out.println(“s1 == s2= ” +result122); System.out.println(“s1 equals s3= ” +result131); System.out.println(“s1 == s3= ” +result132); System.out.println(“s1 equals s4= ” +result141); System.out.println(“s1 == s4= ” +result142); System.out.println(“s1 equals s5= ” +result151); System.out.println(“s1 == s5= ” +result152);} }(8)判斷回文字符串 回文是一種“從前向后讀”和“從后向前讀”都相同的字符串。如“rotor”是一個回文字符串。 程序中使用了兩種算法來判斷回文字符串: 算法一:分別從前向后和從后向前依次獲得原串str的一個字符ch1、ch2,比較ch1和ch2,如果不相等,則str肯定不是回文串,yes=false,立即退出循環(huán):否則繼續(xù)比較,直到字符全部比較完,yes的值仍為true,才能肯定str是回文串。 算法二:將原串str反轉(zhuǎn)成temp串,再比較兩串,如果相等則是回文字符串。(9)使用String類的compareTo(String s)方法,對以下字符串從小到大排序:“melon”, “apple”, “pear”, “banana”,顯示輸出排序結(jié)果。 要求: (1)編譯調(diào)試程序之前應(yīng)配置好環(huán)境變量; (2)要分別掌握用JDK命令行和Eclipse集成開發(fā)環(huán)境調(diào)試Java程序;(3)注意Java兩大類程序:應(yīng)用程序和小程序的區(qū)別。 程序清單: (建議程序中適當(dāng)添加注釋信息,增強(qiáng)可讀性;較長程序可分欄書寫,保證報(bào)告排版整潔美觀。) (1)主方法傳遞參數(shù)“Hello world”字符串,并輸出 public class Hello { public Hello(){ System.out.println(“HelloWorld!”);} public static void main(String args[]){ new Hello();} }(2)Eclipse編譯Java Applet import java.awt.*;import java.applet.Applet;public class HelloApplet extends Applet { int height,width;public void init(){ this.height=100; this.width=300;} public void paint(Graphics g){ g.setColor(Color.red); g.drawString(“Hello!”, 20, 20);} }(3) package b;import java.util.Scanner;public class Test { public static void main(String args[]){ int score; //char grade; System.out.println(“請輸入分?jǐn)?shù)按回車”); Scanner reader=new Scanner(System.in); score=reader.nextInt(); if(score>=90&&score<=100){ System.out.println(“A”); } else if(score>=70&&score<=89){ System.out.println(“B”); } else if(score>=60&&score<=69){ System.out.println(“C”); } else if(score<60){ System.out.println(“D”); } else{ System.out.println(“數(shù)據(jù)錯誤”); } } }(4) public class Lim { public static void main(String[] args){ int[] prime = calculation(20, 200, 300); for(int i = 0;i < prime.length;i++){ if(prime[i]!= 0){ if(i % 10 == 0 && i!= 0) System.out.println(); System.out.print(prime[i] + “ ”);// 打印數(shù)據(jù) } } } public static int[] calculation(int length, int start, int end){ int j; int step = 0; int[] prime = new int[length]; for(int i = start;i <= end;i++) { j = 2; while(i % j!= 0){ j++; } if(j == i) { prime[step] = i; step++; } } return prime; } }(5)① public class shuzu { public static void main(String args[]){ int i,j; int arr[][]=new int[4][]; for(i=0;i arr[i]=new int[arr.length];for(i=0;i<4;i++) for(j=3;j>=i;j--){ arr[i][j]=i; } for(j=0;j<4;j++){ for(i=3;i>=j;i--){ arr[i][j]=j; } } for(i=0;i<=3;i++){ for(j=0;j<=3;j++){ System.out.print(arr[i][j]); System.out.print(“ ”); } System.out.println(); } } } ②public class Shuzu { public static void main(String args[]){ int num[][]=new int[4][];for(int i=0;i num[i]=new int[2*i+1]; for(int m=0;m System.out.print(“ ”); } int k=i+1; for(int j=0;j if(j<=i) num[i][j]=j+1; else{ k--; num[i][j]=k; } System.out.print(num[i][j]+“ ”); } System.out.println();} } }(6)public class test { public static void main(String[] args){ // TODO Auto-generated method stub int[][] mat = {{11,12,13},{4,5,6},{7,8,9}}; for(int i=0;i { for(int j=0;j System.out.print(mat[i][j]+“ ”); System.out.println(); } boolean find = false;//找到鞍點(diǎn)標(biāo)記 int row=0;//第1行下標(biāo) int max=0;//記錄當(dāng)前行最大值的列下標(biāo) while(!find && row { max=0;//初始設(shè)每行第1列值最大 for(int j=1;j if(mat[row][j]>mat[row][max])//mat[row][max]為該行最大值 max = j; boolean yes = true;//再判斷mat[row][max]是否在列上最小 int j=0; while(yes && j { if(mat[j][max] yes=false; j++; } if(yes) find = true; else row++; } if(find) System.out.println(“The dort: ”+mat[row][max]); else System.out.println(“The dort: null”);} }(8)import java.util.Scanner;public class HuiWenTest { public static void main(String[] args){ // TODO Auto-generated method stub System.out.println(“請輸入一個字符串”);@SuppressWarnings(“resource”) Scanner input = new Scanner(System.in);String str = input.next();StringBuilder sb=new StringBuilder(str);sb.reverse();//將Sr倒置的方法 String newStr=new String(sb);if(str.equals(newStr)){ System.out.println(str+“是回文字符串”);}else{ System.out.println(str+“不是回文字符串”);} } }(9)import java.util.*;public class SortString { public static void main(String[] args){ // TODO Auto-generated method stub String [ ] a={“melon”,“apple”,“pear”,“banana”}; String [ ] b=Arrays.copyOf(a,a.length);System.out.println(“使用用戶編寫的SortString類,按字典序排列數(shù)組a:”);SortString.sort(a);System.out.println(“排序結(jié)果是:”);for(String s:a){ System.out.print(“ ”+s);} System.out.println(“");System.out.println(”使用類庫中的Arrays類,按字典序排列數(shù)組b:“);Arrays.sort(b);System.out.println(”排序結(jié)果是:“);for(String s:b){ System.out.print(” “+s);} } 四、實(shí)驗(yàn)結(jié)果與分析(程序運(yùn)行結(jié)果及其分析) (1) (2) (3) (4) (5) (6) (7) (8) (9) 五、實(shí)驗(yàn)體會(遇到問題及解決辦法,編程后的心得體會) 在這次實(shí)驗(yàn)中,我知道了eclipse和jdk運(yùn)行程序的區(qū)別,jdk比較麻煩一些,需要配置變量。在實(shí)驗(yàn)中,配置jdk的環(huán)境變量要注意它的path和 classpath,如果classpath本身就有,可以在后面加分號,這樣不影響其它的classpath的使用。學(xué)會了如何生成注釋文檔,主函數(shù)傳遞參數(shù)的方法,還有壓縮文件,實(shí)驗(yàn)中還對數(shù)組的創(chuàng)建和使用進(jìn)行了練習(xí),還有一些類的應(yīng)用。 實(shí)驗(yàn)項(xiàng)目名稱: 面向?qū)ο缶幊?實(shí)驗(yàn)學(xué)時(shí): 8 同組學(xué)生姓名: ———— 實(shí)驗(yàn)地點(diǎn): 工科樓A101 實(shí)驗(yàn)日期: 17.4.11~17.5.2 實(shí)驗(yàn)成績: 批改教師: 劉晶 批改時(shí)間: 實(shí)驗(yàn)2 面向?qū)ο缶幊?/p> 一、實(shí)驗(yàn)?zāi)康暮鸵?/p> (1)熟練掌握J(rèn)ava語言類定義的基本語法;(2)熟練掌握類成員的訪問控制,對象建立的方法;(3)熟練掌握類構(gòu)造方法、成員方法的定義和重載;(4)熟練掌握類繼承、多態(tài)和抽象性;(5)熟練掌握接口的定義和實(shí)現(xiàn)方法;(6)掌握基本的異常處理方法; (7)調(diào)試程序要記錄調(diào)試過程中出現(xiàn)的問題及解決辦法; (8)編寫程序要規(guī)范、正確,上機(jī)調(diào)試過程和結(jié)果要有記錄,不斷積累編程及調(diào)試經(jīng)驗(yàn); (9)做完實(shí)驗(yàn)后給出本實(shí)驗(yàn)的實(shí)驗(yàn)報(bào)告。 二、實(shí)驗(yàn)儀器和設(shè)備 奔騰以上計(jì)算機(jī),Windows 操作系統(tǒng),裝有JDK1.6和Eclipse4.2軟件。 三、實(shí)驗(yàn)過程 (1)定義一個Man類,保存在Man.java文件中,類中包含說話方法如下: public class Man { public void say() { System.out.println(“我是中國人!”); } } 為此類打包為cn.edu.jit.chinese;再在Man.java文件所在路徑下,創(chuàng)建一個China.java文件,其中定義China類如下: public class China { public static void main(String[] args) { Man lihua = new Man(); lihua.say(); } } 在China類中引用Man類,輸出顯示“我是中國人!”。試著去掉Man類的public修飾,看看會發(fā)生什么情況? (2)設(shè)計(jì)復(fù)數(shù)類,成員變量包括實(shí)部和虛部,成員方法包括實(shí)現(xiàn)復(fù)數(shù)加法、減法、字符串描述、比較是否相等等操作。 (3)包的建立與使用:設(shè)計(jì)計(jì)算器類Calculator,計(jì)算加、減、乘、除和立方體體積,并且打包為mypackage。觀察源文件目錄下是否生成了mypackage文件夾,在該文件夾中是否有Calculate.class文件。編輯PackageDemo.java,保存在Calculator.java同一目錄下,引用計(jì)算器類的各方法顯示計(jì)算結(jié)果。 (4)試編碼實(shí)現(xiàn)簡單的銀行業(yè)務(wù):處理簡單帳戶存取款、查詢。編寫銀行帳戶類BankAccount,包含數(shù)據(jù)成員:余額(balance)、利率(interest);操作方法:查詢余額、存款、取款、查詢利率、設(shè)置利率。再編寫主類UseAccount,包含main()方法,創(chuàng)建BankAccount類的對象,并完成相應(yīng)操作。 (5)假定根據(jù)學(xué)生的3門學(xué)位課程的分?jǐn)?shù)決定其是否可以拿到學(xué)位,對于本科生,如果3門課程的平均分?jǐn)?shù)超過60分即表示通過,而對于研究生,則需要平均超過80分才能夠通過。根據(jù)上述要求,請完成以下Java類的設(shè)計(jì): 1)設(shè)計(jì)一個基類Student描述學(xué)生的共同特征。 2)設(shè)計(jì)一個描述本科生的類Undergraduate,該類繼承并擴(kuò)展Student類。3)設(shè)計(jì)一個描述研究生的類Graduate,該類繼承并擴(kuò)展Student類。 4)設(shè)計(jì)一個測試類StudentDemo,分別創(chuàng)建本科生和研究生這兩個類的對象,并輸出相關(guān)信息。 (6)設(shè)計(jì)三角形類,繼承圖形抽象類,計(jì)算三角形面積和周長。 (7)試編碼實(shí)現(xiàn)多態(tài)在工資系統(tǒng)中的應(yīng)用:給出一個根據(jù)雇員類型利用abstract方法和多態(tài)性完成工資單計(jì)算的程序。Employee是抽象類,Employee的子類有Boss(每星期發(fā)給他固定工資,而不計(jì)工作時(shí)間)、CommissionWorker(除基本工資外還根據(jù)銷售額發(fā)放浮動工資)、PieceWorker(按其生產(chǎn)的產(chǎn)品數(shù)發(fā)放工資)、HourlyWorker(根據(jù)工作時(shí)間長短發(fā)放工資)。該例的Employee的每個子類都聲明為final,因?yàn)椴恍枰倮^承它們生成子類。在主測試類Test中測試各類雇員工資計(jì)算結(jié)果。 提示:對所有雇員類型都使用earnings()方法,但每個人掙的工資按他所屬的雇員類計(jì)算,所有雇員類都是從超類Employee派生出的。在超類中聲明earnings()為抽象方法,并且對于每個子類都提供恰當(dāng)?shù)膃arnings()的實(shí)現(xiàn)方法。為了計(jì)算雇員的工資,程序僅僅使用雇員對象的一個超類引用并調(diào)用earnings()方法。在一個實(shí)際的工資系統(tǒng)中,各種Employee對象的引用可以通過一個Employee引用數(shù)組來實(shí)現(xiàn)。程序依次使用數(shù)組的每個元素(Employee引用)調(diào)用每個對象的earnings()方法。Employee類定義如下: abstract class Employee { private String firstName;private String lastName;public Employee(String first,String last){ firstName=first;lastName=last;} public String getEmployeeName(){ return firstName;} public String getLastName(){ return lastName;} public String toString(){ return firstName+lastName;} public abstract String earnings();}(8)設(shè)計(jì)圓柱體類和圓椎體類,繼承圓類Circle并實(shí)現(xiàn)體積接口Volume,計(jì)算表面積和體積。 (9)定義一個接口CanFly,描述會飛的方法public void fly();分別定義飛機(jī)類和鳥類,實(shí)現(xiàn)CanFly接口。定義一個測試類,測試飛機(jī)和鳥。測試類中定義一個makeFly(CanFly obj)方法,讓會飛的事物飛起來(即調(diào)用相應(yīng)類的fly()方法)。然后在main方法中創(chuàng)建飛機(jī)對象和鳥對象,并在main方法中調(diào)用makeFly(CanFly obj)方法,讓飛機(jī)和鳥起飛。 (10)異常的捕獲:計(jì)算兩數(shù)相除并輸出結(jié)果。使用三個catch子句,分別捕捉輸入輸出異常、除數(shù)為0的異常和參數(shù)輸入有誤異常。import java.io.*;class Ex1 { public static void main(String args[ ]){ try{ BufferedReader strin=new BufferedReader(new InputStreamReader(System.in));//建立輸入流緩沖區(qū) System.out.print(”請輸入除數(shù):“);String cl=strin.readLine();//鍵盤輸入 int a=Integer.parseInt(cl);System.out.print(”請輸入被除數(shù):“);cl=strin.readLine();int b=Integer.parseInt(cl);int c=b/a;System.out.println(”商為:“+c);} //捕獲與I/O有關(guān)的異常(空白處補(bǔ)全捕獲語句) //捕獲數(shù)值轉(zhuǎn)化時(shí)的異常,如不能將字符轉(zhuǎn)化成數(shù)值 //捕獲除數(shù)為0的異常 } } 編譯并運(yùn)行,當(dāng)產(chǎn)生輸入輸出異常時(shí)顯示異常信息;當(dāng)輸入除數(shù)為0時(shí),出現(xiàn)算術(shù)異常,提示除數(shù)為0,并要求重新輸入;當(dāng)輸入的不是整數(shù)時(shí),如將30輸成了3o,出現(xiàn)數(shù)值格式異常,提示輸入整數(shù)。 (11)編寫程序包含自定義異常MyException,當(dāng)100被13和4除時(shí)拋出該異常,其余除數(shù)顯示商值。 要求: (1)注意選用適當(dāng)?shù)念惓蓡T修飾符(private、protected、public等),比較它們的使用情況; (2)養(yǎng)成良好的編程習(xí)慣,嚴(yán)格按照命名規(guī)則為包、類及類成員命名,將每個程序打包,包的命名方式如two.num1表示實(shí)驗(yàn)二的第一題; (3)學(xué)會使用Eclipse的各種調(diào)試方法; (4)學(xué)會查閱Java API文檔,如查找異常類的使用方法。 程序清單: (建議程序中適當(dāng)添加注釋信息,增強(qiáng)可讀性;較長程序可分欄書寫,保證報(bào)告排版整潔美觀。)(1)package cn.edu.jit.chinese;// 為Man類打包為cn.edu.jit.chinese public class Man { public void say(){ System.out.println(”我是中國人!“);} } package cn.edu.jit.chinese; import cn.edu.jit.chinese.*;//導(dǎo)入包 public class China { public static void main(String[] args){ Man lihua = new Man();//主方法先創(chuàng)建類然后調(diào)用類 lihua.say();} }(2)public class Complex { private double real,image;//定義私有的real,image public Complex(double real,double image) {this.real=real;//賦值 this.image=image;} public Complex(double real){this(real,0);} public Complex(){this(0,0);} public Complex(Complex c){this(c.real,c.image);} public double getReal(){return real;} public void setReal(double real){ this.real = real;} public double getImage(){ return image;} public void setImage(double image){ this.image = image;} public Complex add(Complex c1,Complex c2)//寫方法 {Complex C=new Complex(c1.real+c2.real,c1.image+c2.image);return C;} public Complex add(Complex c1){Complex C=new Complex(this.real+c1.real,this.image+c1.image);return C;} public Complex jian(Complex c1,Complex c2){Complex C=new Complex(c1.real-c2.real,c1.image-c2.image);return C;} public Complex jian(Complex c1){Complex C=new Complex(this.real-c1.real,this.image-c1.image);return C;} public boolean bijiao(Complex c1,Complex c2){return(c1.real==c2.real&&c1.image==c2.image);} public boolean bijiao(Complex c1){return(c1.real==this.real&&c1.image==this.image);} public String toString(){return this.real+”+“+this.image+”i“;} } public class ComplexText { public static void main(String[] args){ Complex c1=new Complex(2,5);//創(chuàng)建類,調(diào)用類里面的方法 Complex c2=new Complex(5,2); Complex c3=new Complex(); System.out.println(c3.add(c1,c2)); System.out.println(c3.jian(c1,c2)); System.out.println(c3.bijiao(c1,c2));} }(3)public class Calculate { double i,j, t;public Calculate(int i,int j){this.i=i;this.j=j;} public Calculate(int i,int j,int t){this.i=i;this.j=j;this.t=t;} public double add(){return i+j;} public double jian(){return i-j;} public double cheng(){return i*j;} public double chu(){return i/j;} public double tiji(){return i*i*i+j*j*j+t*t*t;} } public class PackageDemo {//測試 public static void main(String[] args){ Calculate c1=new Calculate(8,4); Calculate c2=new Calculate(8,4,2); System.out.println(”相加=“+c1.add()); System.out.println(”相減=“+c1.jian()); System.out.println(”相乘=“+c1.cheng()); System.out.println(”相除 =“+c1.chu()); System.out.println(”立方體體積=“+c2.tiji());} }(4)public class BankAccount { double balance,interest,cunkuan;public BankAccount(double cunkuan,double balance)//寫方法 {this.balance=balance; this.cunkuan=cunkuan;} public void set(double cunkuan) {if(cunkuan<10000)interest=0.1; else if(cunkuan<50000)interest=0.25; else if(cunkuan<100000)interest=0.035; else interest=0.5;} public double get() { return interest;} public void chaxun(double balance,double cunkuan) {System.out.println(”存款為:“+cunkuan); System.out.println(”余額為:“+balance);} public void qu(double qukuan) {System.out.println(”取款為:“+qukuan);System.out.println(”得到的利潤率:“+(this.cunkuan-qukuan)*this.interest);} } public class UseAccount {//測試 public static void main(String[] args){ BankAccount c1=new BankAccount(40000,40000); c1.chaxun(40000,20000); c1.set(20000); System.out.println(”利率為“+c1.get()); c1.qu(10000);} }(5)public class Student { String name;int age;float average,chainese;float math,Enghish;public Student(String name,int age){this.name=name;this.age=age;System.out.println(name+”:“+age+”歲“+” “);} public void set(float chinese,float math,float Enghish){average=(chinese+math+Enghish)/3;} public float get(){return average;} } class Undergraduate extends Student// Student繼承Undergraduate {public Undergraduate(String name,int age){ super(name,age);} public void hege(float average){ this.average=average; if(average>=60)System.out.println(”本科生成績合格“);else System.out.println(”本科生成績不合格“);}} class Graduate extends Student// Student繼承Graduate {public Graduate(String name,int age){ super(name,age);//調(diào)用 } public void hege(float average){ this.average=average;if(average>=80)System.out.println(”研究生生成績合格“);else System.out.println(”研究生成績不合格“);} } public class StudentDemo {//測試 public static void main(String[] args){ Undergraduate c1=new Undergraduate(”小明 “,22); System.out.println(”本科生三門成績分別為:“+”59,“+”85,“+”90“); c1.set(65,75,60); System.out.println(”本科生平均分=“+c1.get()); c1.hege(c1.get()); System.out.println(); Graduate c2=new Graduate(”小紅 “,18); System.out.println(”研究生生三門成績分別為“+”90,“+”84,“+”88“); c2.set(80,86,79); System.out.println(”研究生生平均分=“+c2.get()); c2.hege(c2.get());}(6)public abstract class ClosedFigure {//定義抽象類 String shape;public ClosedFigure(String newShape){this.shape=newShape;} public abstract double perimeter();//定義抽象類,里面不能寫方法 public abstract double area();} public class Triangle extends ClosedFigure {// ClosedFigure繼承Triangle double a,b,c;public Triangle(String newShape,double a,double b,double c){super(”newShape“);this.a=a;this.b=b; this.c=c;} public double perimeter(){return a+b+c;} public double area(){double s;s=(a+b+c)/2;return Math.sqrt(s*(s-a)*(s-b)*(s-c));} public String toString(){return(”三角形三邊長:“+a+” “+b+” “+c+” “+”周長:“+perimeter()+”面積:“+area());} public class Test { public static void main(String[] args){ Triangle c1=new Triangle(”三角形“,3,4,5); c1.perimeter(); c1.area(); System.out.println(c1.toString());} } }(7)public abstract class Employee { private String firstName;private String lastName;public Employee(String first,String last) {firstName=first; lastName=last;} public String getEmployeeName() {return firstName;} public String getLastName() { return lastName;} public String toString() {return firstName+lastName;} public abstract String earnings();} public final class Boss extends Employee{ double salary;public Boss(String first, String last, double salary){ super(first, last); this.salary = salary;} public String earnings(){return(salary+”“);} } public final class CommissionWorker extends Employee { double salary; double sale;double price;public CommissionWorker(String first, String last, double salary, double sale,double price){ super(first, last); this.salary = salary; this.sale = sale; this.price = price;} public String earnings(){return(salary+sale*price+”“);} } public final class PieceWorker extends Employee{ double number; double price; public PieceWorker(String first, String last, double number,double price){ super(first, last); this.number = number; this.price=price; } public String earnings() {return(number*price+”“);} } public final class HourlyWorker extends Employee {double time;double money;public HourlyWorker(String first, String last, double time, double money){ super(first, last);this.time = time;this.money = money;} public String earnings(){ return(time*money+”“);} } public class Test { public static void main(String[] args){ Employee c1=new Boss(”張“,”三“,10000); System.out.println(”張三月工資:“+c1.earnings()); Employee c2=new CommissionWorker(”李“,”四“,4000,1500,2); System.out.println(”李四月工資:“+c2.earnings()); Employee c3=new PieceWorker(”王“,”五“,1000,3); System.out.println(”王五月工資:“+c3.earnings()); Employee c4=new HourlyWorker(”劉“,”三“,600,30); System.out.println(”劉三月工資:“+c4.earnings());} }(8)public class Circle { String shape;double r;double height;double pi;public Circle(String shape,double r,double height,double pi){this.shape=shape;this.height=height;this.r=r;this.pi=pi;} } public interface Volume { public abstract double area();public abstract double NewVolume();} public class Yuanzhu extends Circle implements Volume { public Yuanzhu(String shape, double r, double height, double pi){ super(shape, r, height, pi);} public double area(){ return pi*r*r;} public double NewVolume(){return area()*height;} } public class Yuanzhui extends Yuanzhu implements Volume { public Yuanzhui(String shape, double r, double height, double pi){ super(shape, r, height, pi); // TODO Auto-generated constructor stub } double s;public double area(){s=Math.sqrt(height*height+r*r);return pi*r*s+pi*r*r;} public double NewVolum(){return 1.0/3*pi*r*pi*r*height;} } public class Test { public static void main(String[] args){ Yuanzhu c1=new Yuanzhu(”圓柱“,4,6,3.14); Yuanzhui c2=new Yuanzhui(”圓錐“,2,3,3.14); System.out.println(”圓柱表面積:“+c1.area()); System.out.println(”圓柱體積:“+c1.NewVolume()); System.out.println(”圓錐表面積:“+c2.area()); System.out.println(”圓錐體積:“+c2.NewVolume());} }(9)public interface CanFly {//定義接口CanFly public void fly();} public class Plane implements CanFly{//使用接口 @Override public void fly(){ // TODO Auto-generated method stub System.out.println(”飛機(jī)借助螺旋槳飛上天空“);} } public class Bird implements CanFly{ @Override public void fly(){ // TODO Auto-generated method stub System.out.println(”小鳥 借助翅膀飛上天空“);} } public class Test { static void makeFly(CanFly obj){ obj.fly();} public static void main(String[] args){ // TODO Auto-generated method stub CanFly p =new Plane(); makeFly(p); CanFly b =new Bird(); makeFly(b);} }(10)import java.io.*;public class Ex1 { public static void main(String args[ ]){ try{ BufferedReader strin=new BufferedReader(new InputStreamReader(System.in));//建立輸入流緩沖區(qū) System.out.print(”請輸入除數(shù):“);String cl=strin.readLine();//鍵盤輸入 int a=Integer.parseInt(cl);System.out.print(”請輸入被除數(shù):“);cl=strin.readLine();int b=Integer.parseInt(cl);int c=b/a;System.out.println(”商為:“+c);} //捕獲與I/O有關(guān)的異常(空白處補(bǔ)全捕獲語句) catch(IOException e){System.out.println(”輸入輸出異常“);} //捕獲數(shù)值轉(zhuǎn)化時(shí)的異常,如不能將字符轉(zhuǎn)化成數(shù)值 catch(NumberFormatException e){System.out.println(”數(shù)值格式異常,重新輸入“); } //捕獲除數(shù)為0的異常 catch(ArithmeticException e){System.out.println(”除數(shù)為0,重新輸入“);} } }(11)(1)MyException類: package exp2_11;public class MyException extends Exception{ MyException(String msg){ super(msg);} }(2)Div主類: package exp2_11;import java.io.*;public class Div { public static void main(String args[])throws MyException{ try{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print(”請輸入實(shí)數(shù)除法運(yùn)算的被除數(shù):“); String str = in.readLine(); double a = Double.parseDouble(str); System.out.print(”請輸入除數(shù):“); str = in.readLine(); double b = Double.parseDouble(str); System.out.println(”商結(jié)果:“+division(a,b)); } catch(ArithmeticException e1){ System.out.println(”商結(jié)果:Infinity“+e1); System.out.println(”商結(jié)果:NaN“+e1); } catch(NumberFormatException e2){ System.out.println(”異常:字符串不能轉(zhuǎn)換成整數(shù)!“+e2); } catch(IOException e3){ System.out.println(”異常:IO異常“+e3); } finally{ System.out.println(”程序結(jié)束!“); } } static double division(double a,double b)throws MyException{ if(a==100 &&(b==4 || b==13)) throw new MyException(”不符規(guī)范“); else return(a/b);} } 四、實(shí)驗(yàn)結(jié)果與分析(程序運(yùn)行結(jié)果及其分析) (1) 去掉Man類的public修飾,程序運(yùn)行不出來,提示缺少M(fèi)an的公開方法。(2) (3) (4) (5) (6) (7) (8) (9) (10) (11) 五、實(shí)驗(yàn)體會(遇到問題及解決辦法,編程后的心得體會) 學(xué)習(xí)程序設(shè)計(jì)的基本目的就是培養(yǎng)描述實(shí)際問題的程序化解決方案的關(guān)鍵技能Java面向?qū)ο蟪绦蛟O(shè)計(jì)是一門實(shí)踐性比較強(qiáng)的課程在實(shí)際中我們必須把理論和實(shí)踐結(jié)合起來。在實(shí)驗(yàn)中我們對照課本的知識然后進(jìn)行實(shí)際的操作而后發(fā)現(xiàn)實(shí)際的運(yùn)用比課本提到的要多很多理論總是來源于實(shí)踐我們必須在現(xiàn)有的理論的基礎(chǔ)上進(jìn)行有效地實(shí)踐。而這次實(shí)驗(yàn)也讓我看到了現(xiàn)在學(xué)習(xí)的一個很大弱點(diǎn)就是實(shí)踐的實(shí)踐往往很少。在現(xiàn)實(shí)社會中我們必須懂得實(shí)際的操作才能更好的服務(wù)于社會。所以我必須在以后的學(xué)習(xí)中多動手多實(shí)際操作爭取能在實(shí)踐中找到屬于自己新的感悟,終于在學(xué)習(xí)Java時(shí)達(dá)到了事半功倍的效果。 實(shí)驗(yàn)項(xiàng)目名稱: 圖形用戶界面 實(shí)驗(yàn)學(xué)時(shí): 6 同組學(xué)生姓名: ———— 實(shí)驗(yàn)地點(diǎn): 工科樓A101 實(shí)驗(yàn)日期: 17.5.9~17.5.23 實(shí)驗(yàn)成績: 批改教師: 劉晶 批改時(shí)間: 實(shí)驗(yàn)3 圖形用戶界面 一、實(shí)驗(yàn)?zāi)康暮鸵?/p> (1)掌握Swing組件的使用方法; (2)熟練掌握Swing中常用布局管理器的使用方法;(3)掌握用戶界面動作與事件的處理程序的編寫方法;(4)熟練掌握構(gòu)造用戶界面的方法和常見界面元素的使用;(5)熟練掌握J(rèn)ava繪圖的主要方法。 (6)調(diào)試程序要記錄調(diào)試過程中出現(xiàn)的問題及解決辦法; (7)編寫程序要規(guī)范、正確,上機(jī)調(diào)試過程和結(jié)果要有記錄,不斷積累編程及調(diào)試經(jīng)驗(yàn); (8)做完實(shí)驗(yàn)后給出本實(shí)驗(yàn)的實(shí)驗(yàn)報(bào)告。 二、實(shí)驗(yàn)儀器和設(shè)備 奔騰以上計(jì)算機(jī),Windows 操作系統(tǒng),裝有JDK1.6和Eclipse4.2軟件。 三、實(shí)驗(yàn)過程 1.計(jì)算器設(shè)計(jì) 2.整數(shù)進(jìn)制轉(zhuǎn)換 將一個十進(jìn)制整數(shù)分別轉(zhuǎn)換成二進(jìn)制、八進(jìn)制和十六進(jìn)制整數(shù)。 3.模擬裁判評分。 設(shè)計(jì)如圖所示圖形界面,顯示n個裁判的評分,根據(jù)制定規(guī)則計(jì)算出最后得分。要求:圖形界面采用表格顯示裁判評分,隨裁判人數(shù)變化而變化;指定分?jǐn)?shù)范圍,若超出,則異常處理; 得分規(guī)則有指定接口約定,由多個接口對象給出多種得分規(guī)則,如求平均數(shù)值,或去掉一個最高分和一個最低分后,再求平均值。 4.編譯運(yùn)行下例,然后修改程序,當(dāng)使用鼠標(biāo)單擊后在另一位置重新繪制月亮?!纠?在Applet中畫月亮。import java.awt.*;import java.applet.Applet;public class MoonApplet extends Applet { public void paint(Graphics g)//在Applet上繪圖 { g.setColor(Color.red);g.drawString(”The Moon“,100,20);int x=0,y=0;//圓外切矩形左上角坐標(biāo) x = this.getWidth()/4;y = this.getHeight()/4;int diameter = Math.min(this.getWidth()/2, this.getHeight()/2);//圓的直徑 g.setColor(Color.yellow);g.fillOval(x,y,diameter,diameter);//畫圓 g.setColor(this.getBackground());//設(shè)置為背景色 g.fillOval(x-20,y-20,diameter,diameter);//畫圓 } } 5.根據(jù)阿基米德螺線的極坐標(biāo)方程:r=aθ畫出相應(yīng)圖形。 要求: (1)注意選用適當(dāng)?shù)牟季止芾砥髟O(shè)計(jì)圖形用戶界面,比較它們的布局情況; (2)養(yǎng)成良好的編程習(xí)慣,嚴(yán)格按照命名規(guī)則為包、類及類成員命名,將每個程序打包,包的命名方式如three.num1表示實(shí)驗(yàn)三的第一題;(3)學(xué)會使用Eclipse的各種調(diào)試方法; (4)學(xué)會查閱Java API文檔,如查找事件類的處理里方法。 程序清單: (建議程序中適當(dāng)添加注釋信息,增強(qiáng)可讀性;較長程序可分欄書寫,保證報(bào)告排版整潔美觀。) 1.import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.*;import javax.swing.*; public class Calulator implements ActionListener { JTextField t1;JPanel p1;JFrame f;static int count=1;static float value=0;int p2=0;String p;public Calulator(){f=new JFrame(”Calulator“);f.setSize(400,200);p1=new JPanel();t1=new JTextField(30);t1.setHorizontalAlignment(JTextField.RIGHT);p1.setLayout(new GridLayout(5,4));f.add(t1);String str[]= {”開根“,”+“,”-“,”清零“,”7“,”8“,”9“,”/“,”4“,”5“,”6“,”*“,”1“,”2“,”3“,”負(fù)“,”0“,”.“,”正“,”=“};for(int i=0;i<20;i++){JButton b=new JButton(str[i]);p1.add(b);b.addActionListener(this);} f.add(t1,BorderLayout.CENTER);f.add(p1,BorderLayout.SOUTH);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setVisible(true);} public void actionPerformed(ActionEvent e){ String c = e.getActionCommand();if(c==”0“||c==”1“||c==”2“||c==”3“||c==”4“||c==”5“||c==”6“||c==”7“||c==”8“||c==”9“||c==”.“){if(p2==0){t1.setText(c);p2++;} else {t1.setText(t1.getText()+c);p2++;}} else if(p==”清零“){value=0;t1.setText(String.valueOf(value));} else {count++;p2=0;if(count==2){p=c;value=Float.parseFloat(t1.getText());} if(c==”=“){ if(p==”開根“){value=(float)Math.sqrt(Float.parseFloat(t1.getText()));t1.setText(String.valueOf(value));count-=2;} else if(p==”+“){value+=Float.parseFloat(t1.getText());count-=2;} else if(p==”-“){ value-=Float.parseFloat(t1.getText());count-=2;} else if(p==”*“){value*=Float.parseFloat(t1.getText());count-=2;} else if(p==”/“){ value/=Float.parseFloat(t1.getText());count-=2;} else if(p==”正”){value=Math.abs(Float.parseFloat(t1.getText()));t1.setText(String.valueOf(value));count-=2;} else if(p==”負(fù)“){value=-1*Float.parseFloat(t1.getText());t1.setText(String.valueOf(value));count-=2;} t1.setText(String.valueOf(value));value=0;}} } public static void main(String[] args){ new Calulator();}} 2.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ZhuanH extends JFrame implements ActionListener{ TextField t1,t2,t3,t4;public ZhuanH(){super(”十進(jìn)制整數(shù)轉(zhuǎn)換“);this.setBackground(Color.BLUE);t1=new TextField(5);t2=new TextField(5);t3=new TextField(5);t4=new TextField(5);t1.setText(null);this.setSize(400,200);this.setLayout(new GridLayout(4,2));this.add(new Label(”十進(jìn)制“));this.add(t1);t1.addActionListener(this);this.add(new Label(”二進(jìn)制“));this.add(t2);this.add(new Label(”八進(jìn)制“));this.add(t3);this.add(new Label(”十六進(jìn)制“));this.add(t4);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setVisible(true);} public void actionPerformed(ActionEvent e){ String c = t1.getText();t2.setText(Integer.toBinaryString(Integer.parseInt(c)));t3.setText(Integer.toOctalString(Integer.parseInt(c))); t4.setText(Integer.toHexString(Integer.parseInt(c)));} public static void main(String[] args){ new ZhuanH();}} 3.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class PingFen extends JFrame implements ActionListener{ JPanel p,p1;JTextField t;JTextField t1[]=new JTextField[10];JButton b;float s=0,k;int t2,t3;public PingFen(){ super(”模擬裁判評分“);this.setSize(300,120);p1=new JPanel(new GridLayout(2,5));this.add(p1,”North“);p=new JPanel(new FlowLayout(FlowLayout.RIGHT));this.add(p,”South“);b=new JButton(”平均分“);t=new JTextField(10);p.add(b);p.add(t);for(int i=0;i<10;i++){ t1[i]=new JTextField(6);t1[i].setText(null);p1.add(t1[i]);} b.addActionListener(this);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setVisible(true);} public void actionPerformed(ActionEvent e){float max,min;for(int i=0;i<10;i++){ try{ if(Float.parseFloat(t1[i].getText())>10.0)throw new Exception(); else continue;} catch(Exception ev){JOptionPane.showMessageDialog(this,t1[i].getText()+”超出范圍“+”,“+” 請重新輸入“);t1[i].setText(null);} } max=Float.parseFloat(String.valueOf(t1[0].getText()));min=Float.parseFloat(String.valueOf(t1[0].getText()));for(int i=1;i<10;i++){ if((k=Float.parseFloat(String.valueOf(t1[i].getText())))>max){max=k;t2=i;} else if((k=Float.parseFloat(String.valueOf(t1[i].getText()))) new PingFen();}} 4.import java.awt.*;import java.applet.Applet;import java.awt.event.*;public class MoonApplet extends Applet implements MouseListener { int x,y;public void init(){ x=this.getWidth()/4; y=this.getHeight()/4; addMouseListener(this);} public void paint(Graphics g)//在Applet上繪圖 { g.setColor(Color.red);g.drawString(”The Moon“,100,20);int diameter = Math.min(this.getWidth()/2, this.getHeight()/2);//圓的直徑 g.setColor(Color.yellow);g.fillOval(x,y,diameter,diameter);//畫圓 g.setColor(this.getBackground());//設(shè)置為背景色 g.fillOval(x-20,y-20,diameter,diameter);//畫圓 } public void mouseClicked(MouseEvent e){ x=e.getX();y=e.getY();repaint();} 5.package package2;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class LuoXuan extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L;private LuoXuanCanvas canvas;//自定義畫布組件 public LuoXuan(){super(”阿基米德螺線“);Dimension dim=getToolkit().getScreenSize();this.setBounds(dim.width/4,dim.height/4,dim.width/2,dim.height/2);JPanel p=new JPanel();this.add(p,”North“);JButton b=new JButton(”選擇顏色“);p.add(b);b.addActionListener(this);this.canvas=new LuoXuanCanvas();this.getContentPane().add(this.canvas, ”Center“);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.setVisible(true);} public void actionPerformed(ActionEvent e){Color c=JColorChooser.showDialog(this, ”選擇顏色“, Color.BLUE);this.canvas.setColor(c);this.canvas.repaint();} public static void main(String[] args){ new LuoXuan();} } class LuoXuanCanvas extends Canvas {private Color color;public void LuoXuan(Color color){this.setColor(color);} public void setColor(Color color){this.color=color;} public void paint(Graphics g){int x0=this.getWidth()/2;int y0 = this.getHeight()/2;g.setColor(this.color);g.drawLine(x0, 0, x0, y0*2);g.drawLine(0, y0, x0*2, y0); for(int i=0;i<4000;i++){double angle=i*Math.PI/512;double radius=angle*0.5;int x=(int)Math.round(radius*angle*Math.cos(angle));int y=(int)Math.round(radius*angle*Math.sin(angle));g.drawOval(x0+x, y0+y, 1, 1);} }} 四、實(shí)驗(yàn)結(jié)果與分析(程序運(yùn)行結(jié)果及其分析) (分析每題采用的布局管理器、事件處理類和主要功能實(shí)現(xiàn)方法)1.2.3.4.38 5.五、實(shí)驗(yàn)體會(遇到問題及解決辦法,編程后的心得體會) 這次實(shí)驗(yàn)主要是對圖形用戶界面的設(shè)計(jì),這里有鼠標(biāo)觸發(fā)的事件,就要讓類實(shí)現(xiàn)MouseListener,在類里面實(shí)現(xiàn)MouseListener的方法,這里是選擇單擊時(shí)(mouseClicked()),這個方法,在方法體內(nèi)用getX(),getY()方法來獲取當(dāng)前坐標(biāo)。 實(shí)驗(yàn)項(xiàng)目名稱:Java高級編程 實(shí)驗(yàn)學(xué)時(shí): 4 同組學(xué)生姓名: ———— 實(shí)驗(yàn)地點(diǎn): 工科樓A101 實(shí)驗(yàn)日期: 17.5.30~17.6.6 實(shí)驗(yàn)成績: 批改教師: 劉晶 批改時(shí)間: 實(shí)驗(yàn)4 Java高級編程 一、實(shí)驗(yàn)?zāi)康暮鸵?/p> (1)了解文件的概念和文件對象的創(chuàng)建方法;(2)掌握使用文件輸入輸出流讀寫文件的方法;(3)了解線程的基本概念和多線程程序設(shè)計(jì)的基本方法;(4)掌握數(shù)據(jù)庫連接的方法; (5)創(chuàng)建SQL查詢并更新數(shù)據(jù)庫中的信息; (6)調(diào)試程序要記錄調(diào)試過程中出現(xiàn)的問題及解決辦法; (7)編寫程序要規(guī)范、正確,上機(jī)調(diào)試過程和結(jié)果要有記錄,不斷積累編程及調(diào)試經(jīng)驗(yàn); (8)做完實(shí)驗(yàn)后給出本實(shí)驗(yàn)的實(shí)驗(yàn)報(bào)告。 二、實(shí)驗(yàn)儀器和設(shè)備 奔騰以上計(jì)算機(jī),Windows 操作系統(tǒng),裝有JDK1.6和Eclipse4.2軟件,MySQL數(shù)據(jù)庫。 三、實(shí)驗(yàn)過程 (1)使用文件字節(jié)輸入/輸出流,合并兩個指定文件;當(dāng)文件中的數(shù)據(jù)已排序時(shí),合并后的數(shù)據(jù)也要求是已排序的。 (2)將Java的關(guān)鍵字保存在一個文本文件中,判斷一個字符串是否為Java的關(guān)鍵字。(3)編寫在構(gòu)造方法中產(chǎn)生一個1-5之間的隨機(jī)數(shù)的繼承Thread類的線程類DelayPrintThread,使得線程體每休眠此隨機(jī)數(shù)時(shí)間就打印輸出線程號和休眠時(shí)間;另外編寫應(yīng)用DelayPrintThread類的Java應(yīng)用程序TwoThread.java,在main()方法中創(chuàng)建兩個線程,并應(yīng)用sleep()控制主應(yīng)用程序延遲一段時(shí)間。 (4)編寫繼承Runnable接口的Applet多線程小程序類MultiThreadApplet,編寫繼承該類的Applet小程序類Clock,在Clock中重新構(gòu)造父類的run()方法,實(shí)現(xiàn)數(shù)字時(shí)鐘的功能,要求不斷刷新顯示時(shí)、分、秒。 (5)為學(xué)生信息表stuinfo設(shè)計(jì)數(shù)據(jù)庫應(yīng)用程序,包括數(shù)據(jù)的輸入、刪除和查詢功能。 要求: (1)注意選用適當(dāng)?shù)奈募鬟M(jìn)行文件讀寫; (2)學(xué)會兩種創(chuàng)建線程的方法,并比較使用場合; (3)養(yǎng)成良好的編程習(xí)慣,嚴(yán)格按照命名規(guī)則為包、類及類成員命名,將每個程序打包,包的命名方式如four.num1表示實(shí)驗(yàn)四的第一題;(4)學(xué)會查閱Java API文檔,如查找常用工具類。 程序清單: (建議程序中適當(dāng)添加注釋信息,增強(qiáng)可讀性;較長程序可分欄書寫,保證報(bào)告排版整潔美觀。)1.import java.io.*;import java.util.Arrays;public class File { private String Filename;static int s=0,t=0;public File(String Filename){this.Filename=Filename;} public void writeToFile(byte[] buffer)throws IOException {if(s==0){FileOutputStream fout = new FileOutputStream(this.Filename);s++;Arrays.sort(buffer);fout.write(buffer);this.readFromFile();fout.close();} else { FileOutputStream fout1 = new FileOutputStream(this.Filename,true);Arrays.sort(buffer);fout1.write(buffer);fout1.close();} } public void readFromFile()throws IOException { FileInputStream fin = new FileInputStream(this.Filename);if(t==0){System.out.println(”文件名“+”:“+this.Filename+”:“);t++;} else System.out.println(”合并兩個文件后“+”:“+this.Filename+”:“);byte[] buffer = new byte[512];int count = fin.read(buffer);while(count!=-1){ for(int i=0;i byte[] buffer = {0,1,4,3,2,5,6,9,8,7};byte[] buffer1 = {10,11,12,14,15,17,16,19,20,13,18};File afile = new File(”ByteFile.dat“);afile.writeToFile(buffer);afile.writeToFile(buffer1);afile.readFromFile();} } 2.import java.io.*;public class File { private String Filename;public File(String Filename){this.Filename=Filename;} public void writerLine(String[] s)throws IOException {FileWriter f = new FileWriter(this.Filename);System.out.println(this.Filename+”文件中的java關(guān)鍵字有“+”:“);for(int i=0;i public void Text(String[] s,String[] s1){int i,j;for(i=0;i if(s1[i]==s[j]) {System.out.println(s1[i]+”是java中的關(guān)鍵字“);break;} else continue;if(j==s.length)System.out.println(s1[i]+”不是java中的關(guān)鍵字“);} } public static void main(String[] args)throws IOException { String[]s={”public“,”class“,”static“,”void“,”String“,”print“,”byte“,”boolean“,”int“,”short“,”long“,”throw“,”cath“,”continue“,”private“,”abstract“,”Interface“,”Exception“};String[] s1={”pblic“,”class“,”string“};File a=new File(”myfile.dat“);a.writerLine(s);a.Text(s,s1);} } 3.public class DelayPrintThread extends Thread{ private int number,time;public DelayPrintThread(int number) {this.number=number; time=(int)(Math.random()*5);} public void run(){ try { Thread.sleep(this.time);} catch(InterruptedException e){} System.out.println(”線程“+this.number+”:“+”休眠時(shí)間“+this.time);} public class TwoThread { public static void main(String[] args){ DelayPrintThread a=new DelayPrintThread(1);DelayPrintThread b=new DelayPrintThread(2);a.start();b.start();} } 4.import java.applet.Applet;import java.awt.*;import java.util.Date;import java.text.SimpleDateFormat;public class MultiThreadApplet extends Applet implements Runnable { Thread a;public void start(){ if(a==null){a=new Thread(this); a.start();} } public void stop(){ if(a!=null){ a.stop(); a=null;} } public void run(){} public void paint(Graphics g){SimpleDateFormat sdf=new SimpleDateFormat(”yyyy年MM月dd日E a hh時(shí) mm分ss秒“);g.drawString(sdf.format(new Date()),50,100);} } public class Clock extends MultiThreadApplet{ public void run(){ repaint();try{a.sleep(1000);} catch(InterruptedException e){} }} 5.import java.sql.*;public class Statement{ public static void main(String args[])throws Exception { Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver“);Connection conn=DriverManager.getConnection(”jdbc:odbc:student“);Statement stmt=conn.createStatement();String Sql=”SELECT stu_id,stu_name,city FROM student WHERE stu_id=5“;String Sql=”INSERT INTO student(stu_id,stu_name,city)VALUES('5','小紅','徐州')“;String Sql=”DELETE FROM student WHERE stu_id=5“;int count=stmt.executeUpdate(Sql);System.out.println(”插入“+count+”行“);ResultSet rs=stmt.executeQuery(Sql);if(rs.next()){System.out.println(”行“+rs.getRow()+”:“+rs.getString(1)+”,“+rs.getString(2)+”,“+rs.getString(3));} else System.out.println(”沒有數(shù)據(jù)“);count=stmt.executeUpdate(Sql);rs=stmt.executeQuery(Sql);if(rs.next()){System.out.println(”行“+rs.getRow()+”:“+rs.getString(1)+”,“+rs.getString(2)+”,“+rs.getString(5));} else System.out.println(”沒有數(shù)據(jù)");} } 四、實(shí)驗(yàn)結(jié)果與分析(程序運(yùn)行結(jié)果及其分析)1.45 2.3.4.五、實(shí)驗(yàn)體會(遇到問題及解決辦法,編程后的心得體會) 通過這次實(shí)驗(yàn),我基本能夠理解線程的運(yùn)行了,學(xué)會調(diào)用Thread類中的系統(tǒng)函數(shù)以及掌握這些函數(shù)的作用是難點(diǎn),start()是開辟一條新線程。子類重寫父類的run()方法,里面用sleep,來控制每個線程的休眠時(shí)間,但是得注意這里應(yīng)該要用try-catch語句來捕獲中斷異常。 河北北方學(xué)院信息科學(xué)與工程學(xué)院 《Java程序設(shè)計(jì)》 實(shí) 驗(yàn) 報(bào) 告 實(shí)驗(yàn)學(xué)期 2014 至 2015 學(xué)年 第 2 學(xué)期 學(xué)生所在系部 信息科學(xué)與工程學(xué)院 年級 2012 專業(yè)班級 電子三班 學(xué)生姓名 馮洋 學(xué)號 201242220 任課教師 實(shí)驗(yàn)成績 實(shí)驗(yàn)七 GUI標(biāo)準(zhǔn)組件及事件處理 一、課程設(shè)計(jì)目的: 《面向?qū)ο蟪绦蛟O(shè)計(jì)》是一門實(shí)踐性很強(qiáng)的計(jì)算機(jī)專業(yè)基礎(chǔ)課程,課程設(shè)計(jì)是學(xué)習(xí)完該課程后進(jìn)行的一次較全面的綜合練習(xí)。其目的在于通過實(shí)踐加深學(xué)生對面向?qū)ο蟪绦蛟O(shè)計(jì)的理論、方法和基礎(chǔ)知識的理解,掌握使用Java語言進(jìn)行面向?qū)ο笤O(shè)計(jì)的基本方法,提高運(yùn)用面向?qū)ο笾R分析實(shí)際問題、解決實(shí)際問題的能力,提高學(xué)生的應(yīng)用能力。 二、實(shí)驗(yàn)要求: 設(shè)計(jì)一個簡單的文本編輯器,具有如下基本功能: 1)所見即所得的文本輸入; 2)能方便地選中文本、復(fù)制、刪除和插入文本; 3)具有一般編輯器所具有的查找和替換功能; 4)簡單的排版,如設(shè)置字體和字號等。 三、課程設(shè)計(jì)說明: 1、需求分析:簡單文本編輯器提供給用戶基本的純文本編輯功能,能夠?qū)⒂脩翡浫氲奈谋敬鎯Φ奖镜卮疟P中。能夠讀取磁盤中現(xiàn)有的純文本文件,以及方便用戶進(jìn)行需要的編輯功能。文件操作能夠?qū)崿F(xiàn)新建、保存、打開文檔等,編輯操作能過實(shí)現(xiàn)文本的剪貼、復(fù)制、粘貼等,格式操作能過實(shí)現(xiàn)字體設(shè)置、背景等,幫助操作能夠?qū)崿F(xiàn)關(guān)于主題的查看等功能 2、概要設(shè)計(jì): (一)其基本功能包括: ① 基本的文本操作功能。包括新建,保存,打開,保存。 ② 基本的編輯功能。包括復(fù)制,剪貼,粘貼。③ 基本的格式功能,字體。④ 簡單的幫助,關(guān)于主題。 (二)主要的組件包括: ① 基本的Frame框架; ② 菜單; ③ 打開文件對話框; ④ 保存文件對話框; ⑤ 顏色對話框; ⑥ 簡單的幫助框架。 3、程序說明: 整個記事本分成:Jframe程序主體框架,Jmenu菜單欄、JtextArea文本輸入?yún)^(qū)、PopupMenu右鍵菜單、JscrollPane滾動條、FonDialog字體類等。 本程序中首先定義一個Java Yang類繼承JFrame作為最底層容器。要想記事本完成需求分析中相應(yīng)的功能,還必須添加事件監(jiān)聽器。事件監(jiān)聽器不僅要添加在菜單欄和內(nèi)容輸入?yún)^(qū),還需加在容器中。本程序中ActListener實(shí)現(xiàn)了ActionListener接口,用來監(jiān)聽并處理所有菜單項(xiàng)和內(nèi)容輸入?yún)^(qū)為事件源的事件。另外,還用來WindowListener來監(jiān)聽處理容器關(guān)閉觸發(fā)的事件,WindowListener繼承了WindowsAdapter類并覆蓋了WindowsClosing方法。 四、程序調(diào)試: 1、調(diào)試分析: (1)關(guān)于打開、保存和退出我運(yùn)用了文件對話框, openFileDialog、saveFileDialog和System.exit()以及文件輸入輸出流來實(shí)現(xiàn),新建功能我選用了 textArea.setText()方法.(2)對于剪貼,粘貼,復(fù)制的實(shí)現(xiàn)則用 復(fù)制 String text = textArea.getSelectedText();StringSelection selection= new StringSelection(text);clipboard.setContents(selection,null);粘貼 Transferable contents = clipboard.getContents(this);if(contents==null)return;String text;text=“";try { text =(String)contents.getTransferData(DataFlavor.stringFlavor);} catch(Exception ex){ } textArea.replaceRange(text,textArea.getSelectionStart(),textArea.getSelectionEnd());(3)至于字體功能的實(shí)現(xiàn),則是新建了一個字體類,在這個類中設(shè)置了字形,字體以及大小并且有字體樣式可預(yù)覽用戶當(dāng)前的設(shè)置。FlowLayout()設(shè)置布局,setSize()設(shè)置大小add()添加需要用的原件。 添加監(jiān)聽器獲取選擇用戶的字號大小 public void itemStateChanged(ItemEvent event){ size =(new Integer((String)event.getItem()).intValue());setCustomFont(new Font(name, type, size));} 設(shè)置字體 private void setCustomFont(Font customFont){ this.customFont = customFont;area.setFont(customFont);area.revalidate();} 獲取字體 public Font getCustomFont(){ return(this.customFont);} 附錄:源代碼 //記事本主體類 import java.awt.event.*;import java.awt.*;import java.io.*;import java.awt.datatransfer.*;import javax.swing.*; import java.awt.print.PrinterException; public class MiniNote extends JFrame implements ActionListener { JMenuBar menuBar = new JMenuBar();JMenu file = new JMenu(”文件(F)“), //菜單 edit = new JMenu(”編輯(E)“), format = new JMenu(”格式(O)“), view = new JMenu(”查看(V)“), help = new JMenu(”幫助(H)“); JMenuItem[] menuItem ={ //菜單下拉項(xiàng) new JMenuItem(”新建(N)“), new JMenuItem(”打開(O)“), new JMenuItem(”保存(S)“), new JMenuItem(”打印(P)“), new JMenuItem(”全選(A)“), new JMenuItem(”復(fù)制(C)“), new JMenuItem(”剪切(T)“), new JMenuItem(”粘貼(P)“), new JMenuItem(”自動換行(W)“), new JMenuItem(”字體(F)“), new JMenuItem(”狀態(tài)欄(S)“), new JMenuItem(”幫助主題(H)“), new JMenuItem(”關(guān)于記事本(A)“), new JMenuItem(”頁面設(shè)置(U)“), new JMenuItem(”退出(X)“), new JMenuItem(”查找(F)“), new JMenuItem(”查找下一個(N)“), new JMenuItem(”替換(R)“)}; JPopupMenu popupMenu = new JPopupMenu();;//右鍵菜單 JMenuItem [] menuItem1 ={ new JMenuItem(”撤銷(Z)“), new JMenuItem(”剪切(X)“), new JMenuItem(”復(fù)制(C)“), new JMenuItem(”粘貼(V)“), new JMenuItem(”刪除(D)“), new JMenuItem(”全選(A)“), }; private JTextArea textArea;//文本區(qū)域 private JScrollPane js;//滾動條 private JPanel jp;private FileDialog openFileDialog;//打開保存對話框 private FileDialog saveFileDialog;private Toolkit toolKit;//獲取默認(rèn)工具包。private Clipboard clipboard;//獲取系統(tǒng)剪切板 private String fileName;//設(shè)置默認(rèn)的文件名 /** * MiniEdit 方法定義 * * 實(shí)現(xiàn)記事本初始化 * **/ public MiniNote(){ fileName = ”無標(biāo)題“;toolKit = Toolkit.getDefaultToolkit();clipboard = toolKit.getSystemClipboard();textArea =new JTextArea();js = new JScrollPane(textArea);jp = new JPanel();openFileDialog = new FileDialog(this,”打開“,FileDialog.LOAD);saveFileDialog = new FileDialog(this,”另存為“,FileDialog.SAVE); js.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);jp.setLayout(new GridLayout(1,1));jp.add(js);textArea.setComponentPopupMenu(popupMenu);//文本區(qū)域添加右鍵 textArea.add(popupMenu);add(jp);setTitle(”迷你記事本“);setFont(new Font(”Times New Roman“,Font.PLAIN,15));setBackground(Color.white);setSize(800,600);setJMenuBar(menuBar);menuBar.add(file);menuBar.add(edit);menuBar.add(format);menuBar.add(view);menuBar.add(help);for(int i=0;i<4;i++){ file.add(menuItem[i]);edit.add(menuItem[i+4]);} for(int i=0;i<3;++i){ edit.add(menuItem[i+15]);} for(int i=0;i<2;++i){ format.add(menuItem[i+8]);help.add(menuItem[i+11]);} view.add(menuItem[10]);file.add(menuItem[14]);for(int i=0;i<6;++i){ popupMenu.add(menuItem1[i]);} //窗口監(jiān)聽 addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ e.getWindow().dispose();System.exit(0);} });//注冊各個菜單項(xiàng)的事件監(jiān)聽器 for(int i=0;i Object eventSource = e.getSource();if(eventSource == menuItem[0])//新建動作 { textArea.setText(”“);} else if(eventSource == menuItem[1])//打開動作 { openFileDialog.setVisible(true);fileName = openFileDialog.getDirectory()+openFileDialog.getFile();if(fileName!= null){ openFile(fileName);} } else if(eventSource ==menuItem[2])//保存動作 { saveFileDialog.setVisible(true);fileName = saveFileDialog.getDirectory()+saveFileDialog.getFile();if(fileName!=null){ writeFile(fileName);} } else if(eventSource==menuItem[14])//退出動作 { System.exit(0);} else if(eventSource == menuItem[4]||eventSource == menuItem1[5])//全選動作 { textArea.selectAll();} else if(eventSource == menuItem[5]||eventSource == menuItem1[2])//復(fù)制動作 { String text = textArea.getSelectedText();StringSelection selection= new StringSelection(text);clipboard.setContents(selection,null);} else if(eventSource == menuItem[6]||eventSource == menuItem1[1])//剪切動作 { String text = textArea.getSelectedText();StringSelection selection = new StringSelection(text);clipboard.setContents(selection,null);textArea.replaceRange(”“, textArea.getSelectionStart(), textArea.getSelectionEnd());} else if(eventSource == menuItem[7]||eventSource == menuItem1[3])//粘貼動作 { Transferable contents = clipboard.getContents(this);if(contents==null)return;String text;text=”“;try { text =(String)contents.getTransferData(DataFlavor.stringFlavor);} catch(Exception ex){ } textArea.replaceRange(text, textArea.getSelectionStart(),textArea.getSelectionEnd());} else if(eventSource == menuItem[8])//自動換行 { if(textArea.getLineWrap())textArea.setLineWrap(false);else textArea.setLineWrap(true); } else if(eventSource == menuItem[9])//字體 {//實(shí)例化字體類 FontDialog fontdialog = new FontDialog(new JFrame(),”字體“,true);textArea.setFont(fontdialog.showFontDialog());//設(shè)置字體 } else if(eventSource == menuItem[11])//幫助 { try { String filePath = ”C:/WINDOWS/Help/notepad.hlp“;Runtime.getRuntime().exec(”cmd.exe /c “+filePath);} catch(Exception ee){ JOptionPane.showMessageDialog(this,”打開系統(tǒng)的記事本幫助文件出錯!“,”錯誤信息“,JOptionPane.INFORMATION_MESSAGE);} } else if(eventSource == menuItem[12])//關(guān)于記事本 { String help = ”記事本 版本1.0n操作系統(tǒng):WIN 8 n編譯器:eclipsen版權(quán)“ + ”所有: ESTON YANG n最終解釋權(quán)歸本人所有“ + ”“ + ”nBuild By 馮洋“ + ”n課程設(shè)計(jì):JAVA“;JOptionPane.showConfirmDialog(null, help, ”關(guān)于記事本“, JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE); } else if(eventSource == menuItem[15]||eventSource == menuItem[16])//查找下一個 { search(); } else if(eventSource == menuItem[17])//替換 { substitude();} else if(eventSource == menuItem[3])//打印 { try { textArea.print();} catch(PrinterException e1){ e1.printStackTrace();} } } /** * openFile方法 * * 從TXT讀進(jìn)數(shù)據(jù)到記事本 * **/ public void openFile(String fileName){ try { File file = new File(fileName);FileReader readIn = new FileReader(file);int size =(int)file.length();int charsRead = 0;char[] content = new char[size];while(readIn.ready()){ charsRead += readIn.read(content,charsRead,size-charsRead);} readIn.close();textArea.setText(new String(content,0,charsRead));} catch(Exception e){ System.out.println(”Error opening file!“);} } /** * saveFile方法 * * 從記事本寫進(jìn)數(shù)據(jù)到TXT * **/ public void writeFile(String fileName){ try { File file = new File(fileName);FileWriter write = new FileWriter(file);write.write(textArea.getText());write.close();} catch(Exception e){ System.out.println(”Error closing file!“);} } /** * substitude方法 * * 實(shí)現(xiàn)替換功能 * */ public void substitude(){ final JDialog findDialog = new JDialog(this, ”查找與替換“, true);Container con = findDialog.getContentPane();con.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel searchContentLabel = new JLabel(”查找內(nèi)容(N):“);JLabel replaceContentLabel = new JLabel(”替換為(P):“);final JTextField findText = new JTextField(30);final JTextField replaceText = new JTextField(30);final JCheckBox matchcase = new JCheckBox(”區(qū)分大小寫(C)“);ButtonGroup bGroup = new ButtonGroup();final JRadioButton up = new JRadioButton(”向上(U)“);final JRadioButton down = new JRadioButton(”向下(D)“);down.setSelected(true);//默認(rèn)向下搜索 bGroup.add(up);bGroup.add(down); JButton searchNext = new JButton(”查找下一個(F)“);JButton replace = new JButton(”替換(R)“);final JButton replaceAll = new JButton(”全部替換(A)“); //”替換“按鈕的事件處理 replace.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(replaceText.getText().length()== 0 && textArea.getSelectedText()!= null) textArea.replaceSelection(”“);if(replaceText.getText().length()> 0 && textArea.getSelectedText()!= null) textArea.replaceSelection(replaceText.getText());} }); //”替換全部“按鈕的事件處理 replaceAll.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ textArea.setCaretPosition(0);//將光標(biāo)放到編輯區(qū)開頭 int a = 0, b = 0, replaceCount = 0;if(findText.getText().length()== 0){ JOptionPane.showMessageDialog(findDialog, ”請?zhí)顚懖檎覂?nèi)容!“, ”提示“,JOptionPane.WARNING_MESSAGE);findText.requestFocus(true);return;} while(a >-1){ int FindStartPos = textArea.getCaretPosition();//獲取光標(biāo)位置 String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase();if(matchcase.isSelected())//大小寫區(qū)分 { strA = str1;strB = str3;} else { strA = str2;strB = str4;} if(up.isSelected())//向上搜索 { if(textArea.getSelectedText()== null){ a = strA.lastIndexOf(strB, FindStartPos1);} } else //向下搜索 { if(textArea.getSelectedText()== null){ a = strA.indexOf(strB, FindStartPos); } else { a = strA.indexOf(strB, FindStartPos-findText.getText().length()+ 1);} } if(a >-1){ if(up.isSelected()){ textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} else if(down.isSelected()){ textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} } else { if(replaceCount == 0){ JOptionPane.showMessageDialog(findDialog,”找不到您查找的內(nèi)容!“, ”記事本“,JOptionPane.INFORMATION_MESSAGE);} else { JOptionPane.showMessageDialog(findDialog, ”成功替換“+ replaceCount + ”個匹配內(nèi)容!“, ”替換成功“,JOptionPane.INFORMATION_MESSAGE);} } if(replaceText.getText().length()== 0&& textArea.getSelectedText()!= null)//用空字符代替選定內(nèi)容 { textArea.replaceSelection(”“);replaceCount++;} if(replaceText.getText().length()> 0&& textArea.getSelectedText()!= null)//用指定字符代替選定內(nèi)容 { textArea.replaceSelection(replaceText.getText());replaceCount++;} }//end while } }); //”查找下一個“按鈕事件處理 searchNext.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ int a = 0, b = 0;int FindStartPos = textArea.getCaretPosition();String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase(); //”區(qū)分大小寫“的CheckBox被選中 if(matchcase.isSelected())//區(qū)分大小寫 { strA = str1;strB = str3;} else //不區(qū)分大小寫 { strA = str2;strB = str4;} if(up.isSelected())//向上搜索 { if(textArea.getSelectedText()== null){ a = strA.lastIndexOf(strB, FindStartPosfindText.getText().length()findText.getText().length()+ 1);} } if(a >-1){ if(up.isSelected()){ textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} else if(down.isSelected()){ textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} } else { JOptionPane.showMessageDialog(null, ”找不到您查找的內(nèi)容!“, ”記事本“, JOptionPane.INFORMATION_MESSAGE);} } }); //”取消“按鈕及事件處理 JButton cancel = new JButton(”取消“);cancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ findDialog.dispose();} });//創(chuàng)建”查找與替換“對話框的界面 JPanel bottomPanel = new JPanel();JPanel centerPanel = new JPanel();JPanel topPanel = new JPanel();JPanel direction = new JPanel(); direction.setBorder(BorderFactory.createTitledBorder(”方向“));direction.add(up);direction.add(down); JPanel replacePanel = new JPanel();replacePanel.setLayout(new GridLayout(1, 2));replacePanel.add(searchNext);replacePanel.add(replace);replacePanel.add(replaceAll);replacePanel.add(cancel); topPanel.add(searchContentLabel);topPanel.add(findText); centerPanel.add(replaceContentLabel);centerPanel.add(replaceText);centerPanel.add(replacePanel); bottomPanel.add(matchcase);bottomPanel.add(direction); con.add(replacePanel);con.add(topPanel);con.add(centerPanel);con.add(bottomPanel); //設(shè)置”查找與替換“對話框的大小、可更改大小(否)、位置和可見性 findDialog.setSize(550, 240);findDialog.setResizable(true);findDialog.setLocation(230, 280);findDialog.setVisible(true);}//方法mySearch()結(jié)束 /** * search方法 * * 實(shí)現(xiàn)查找功能 * */ public void search(){ final JDialog findDialog = new JDialog(this, ”查找下一個“, true);Container con = findDialog.getContentPane();con.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel searchContentLabel = new JLabel(” 查找內(nèi)容(N):“); final JTextField findText = new JTextField(17);final JCheckBox matchcase = new JCheckBox(”區(qū)分大小寫(C)“);ButtonGroup bGroup = new ButtonGroup();final JRadioButton up = new JRadioButton(”向上(U)“);final JRadioButton down = new JRadioButton(”向下(D)“);down.setSelected(true);//默認(rèn)向下搜索 bGroup.add(up);bGroup.add(down); JButton searchNext = new JButton(”查找下一個(F)“); //”查找下一個“按鈕事件處理 searchNext.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ int a = 0, b = 0;int FindStartPos = textArea.getCaretPosition();String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase(); //”區(qū)分大小寫“的CheckBox被選中 if(matchcase.isSelected())//不區(qū)分大小寫 { strA = str1;strB = str3;} else //區(qū)分大小寫 { strA = str2;strB = str4;} if(up.isSelected())//向上搜索 { if(textArea.getSelectedText()== null){ a = strA.lastIndexOf(strB, FindStartPosfindText.getText().length()findText.getText().length()+ 1);} } if(a >-1){ if(up.isSelected()){ textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} else if(down.isSelected()){ textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);} } else { JOptionPane.showMessageDialog(null, ”找不到您查找的內(nèi)容!“, ”記事本“, JOptionPane.INFORMATION_MESSAGE);} } }); //”取消“按鈕及事件處理 JButton cancel = new JButton(” 取消 “);cancel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ findDialog.dispose();} });//創(chuàng)建”替換“對話框的界面 JPanel bottomPanel = new JPanel();JPanel centerPanel = new JPanel();JPanel topPanel = new JPanel();JPanel direction = new JPanel();direction.setBorder(BorderFactory.createTitledBorder(”方向“));direction.add(up);direction.add(down);topPanel.add(searchContentLabel);topPanel.add(findText);topPanel.add(searchNext);bottomPanel.add(matchcase);bottomPanel.add(direction);bottomPanel.add(cancel);con.add(topPanel);con.add(centerPanel);con.add(bottomPanel);//設(shè)置”替換“對話框的大小、可更改大小(否)、位置和可見性 findDialog.setSize(425, 200);findDialog.setResizable(true);findDialog.setLocation(230, 280);findDialog.setVisible(true);} /** * 主函數(shù) * * * **/ public static void main(String[] args){ MiniNote note = new MiniNote();note.setVisible(true);} } //字體類 import java.awt.Font;import java.awt.GraphicsEnvironment;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.border.*;import java.util.*;public class FontDialog { private Dialog fontdialog;private JButton okButton, cancelButton;private int width = 480;private int height = 250;private String name = ”Serif“;private int type = 0;private int size = 12;private Font customFont = new Font(”宋體“, Font.ITALIC, 12);private boolean okpressed = false;private boolean cancelpressed = false;private JLabel lbl1 = new JLabel(”字體:“);private JLabel lbl2 = new JLabel(”字形:“);private JLabel lbl3 = new JLabel(”大?。骸?;private JTextArea area;String[] zx = { ”常規(guī)“, ”加粗“, ”斜體“, ”基線“ };String[] dx = {”8“ , ”9“ , ”10“, ”12“, ”14“, ”15“, ”16“, ”18“,”20“, ”21“, ”22“, ”24“, ”26“, ”28“, ”30“, ”36“,”48“, ”54“,”72“ , ”89“};JLabel lbl = new JLabel(”字體樣式Style“);private JComboBox cb1, cb3 = new JComboBox(dx), cb2 = new JComboBox(zx);private String[] zt; public FontDialog(Frame owner, String title, boolean modal){ init();fontdialog = new Dialog(owner, title, modal);fontdialog.setLocation(owner.getLocation());fontdialog.setLayout(new FlowLayout());fontdialog.setSize(getWidth(), getHeight());fontdialog.add(lbl1);fontdialog.add(cb1);fontdialog.add(lbl2);fontdialog.add(cb2);fontdialog.add(lbl3);fontdialog.add(cb3);fontdialog.add(okButton);fontdialog.add(cancelButton);fontdialog.add(area);fontdialog.setResizable(false);fontdialog.setAlwaysOnTop(true);cancelButton.addActionListener(new fontListener());okButton.addActionListener(new fontListener());fontdialog.addWindowListener(new fontListener()); cb1.addItemListener(new ItemListener(){ // public void itemStateChanged(ItemEvent event){ //獲取選擇用戶的字體類型 name =(String)event.getItem();setCustomFont(new Font(name, type, size));} }); cb2.addItemListener(new ItemListener(){ // public void itemStateChanged(ItemEvent event){ //獲取選擇用戶的字形 String s =(String)event.getItem();if(s.equals(”常規(guī)“)){ type = Font.PLAIN;setCustomFont(new Font(name, type, size));} else if(s.equals(”加粗“)){ type = Font.BOLD; 字體動作 添加監(jiān)聽器字形動作 添加監(jiān)聽器 setCustomFont(new Font(name, type, size));} else if(s.equals(”斜體“)){ type = Font.ITALIC;setCustomFont(new Font(name, type, size));} else { type = Font.CENTER_BASELINE;setCustomFont(new Font(name, type, size));} } }); cb3.addItemListener(new ItemListener(){ //大小動作 public void itemStateChanged(ItemEvent event){ //添加監(jiān)聽器獲取選擇用戶的字號大小 size =(new Integer((String)event.getItem()).intValue());setCustomFont(new Font(name, type, size));} }); } public Font showFontDialog(){ fontdialog.setVisible(true);if(okpressed){ return getCustomFont();} else { return customFont;} } private void init(){ //初始化 okButton = new JButton(”確定“);cancelButton = new JButton(”取消“);GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();zt = ge.getAvailableFontFamilyNames();cb1 = new JComboBox(zt);cb1.setMaximumRowCount(6);area = new JTextArea(6, 30);cb3 = new JComboBox(dx);cb3.setMaximumRowCount(6);okButton.setFocusable(true);area.setEditable(false);area.setText(new Date().toString());area.setBorder(new TitledBorder(”字體樣式"));} public void setWidth(int width){ this.width = width;} public void setHeight(int height){ this.height = height;} private int getWidth(){ return(this.width);} private int getHeight(){ return(this.height);} private void setCustomFont(Font customFont)//{ this.customFont = customFont;area.setFont(customFont);area.revalidate();} public String toString(){ return FontDialog.class.toString();} 設(shè)置字體 public Font getCustomFont()//獲取字體 { return(this.customFont);} private class fontListener extends WindowAdapter implements ActionListener //監(jiān)聽事件類 { public void windowClosing(WindowEvent e){ fontdialog.dispose();} public void actionPerformed(ActionEvent e){ if(e.getSource()== cancelButton){ fontdialog.dispose();cancelpressed = true;} else if(e.getSource()== okButton){ okpressed = true;setCustomFont(new Font(name, type, size));fontdialog.dispose();} } } } 學(xué) 生 實(shí) 驗(yàn) 報(bào) 告 冊 2013——2014學(xué)年第1學(xué)期 項(xiàng)目名稱: Java Web 學(xué)院: 信電 班級: 11計(jì)算機(jī)科學(xué)與技術(shù)一班 學(xué)號: 155140007 姓名: 伍振東 指導(dǎo)教師: 李竹林 完成時(shí)間: 2013/9/28 一、實(shí)驗(yàn)要求 1.用HTML語言編寫如下樣式的網(wǎng)頁 2.可以用Dreamweaver,推薦手動編寫HTML帶代碼 3.圖片從清華大學(xué)的網(wǎng)站自己取得。http://004km.cn“> 文檔為doc格式 實(shí)驗(yàn)報(bào)告一、 實(shí)驗(yàn)?zāi)康?鞏固復(fù)習(xí)課上所講內(nèi)容,進(jìn)一步熟悉面向?qū)ο缶幊獭?二、 實(shí)驗(yàn)內(nèi)容
編寫程序求點(diǎn)到原點(diǎn)的距離三、 程序清單及運(yùn)行結(jié)果
abstractclass Distance
{
abstra...... Java聊天室實(shí)驗(yàn)報(bào)告 班 級:學(xué) 號:姓 名: ****** ******** *** 目錄: 一、實(shí)驗(yàn)?zāi)康?......................................................3 二、所需技術(shù) ...................... 課程名稱: 學(xué)生學(xué)號:學(xué)生姓名: 所屬院部:指導(dǎo)教師: 學(xué)生實(shí)驗(yàn)報(bào)告 (理工類) JAVA程序設(shè)計(jì)專業(yè)班級: 20 15——20 16學(xué)年第2學(xué)期金陵科技學(xué)院教務(wù)處制 實(shí)驗(yàn)項(xiàng)目名稱:JAVA編程基礎(chǔ)實(shí)驗(yàn)...... 實(shí)驗(yàn)項(xiàng)目名稱:實(shí)驗(yàn)4 基于Socket的網(wǎng)絡(luò)編程 【實(shí)驗(yàn)?zāi)康摹?1、 理解Java的基于套接字的網(wǎng)絡(luò)通信原理。 2、 理解客戶端和服務(wù)器的概念。 3、 學(xué)習(xí)使用套接字實(shí)現(xiàn)客戶端和服務(wù)...... 廣東工業(yè)大學(xué)實(shí)驗(yàn)報(bào)告 學(xué)院 專業(yè) 班學(xué)號姓名 成績評定_______ 實(shí)驗(yàn)5 題目繼承與接口實(shí)驗(yàn) 課程名稱Java與面向?qū)ο蟪绦蛟O(shè)計(jì) 一.實(shí)驗(yàn)?zāi)康?(1)學(xué)習(xí)類的繼承、子類在對象中調(diào)用...... Homework3實(shí)驗(yàn)報(bào)告 一、實(shí)驗(yàn)?zāi)康呐c要求 1、掌握J(rèn)ava中類和接口的基本知識; 2、繼承的基本知識; 3、集合的基本操作 二、實(shí)驗(yàn)內(nèi)容 1.PIMCollection 類 創(chuàng)建一個可以管理PIMEnti...... 中 南 民 族 大 學(xué) 實(shí) 驗(yàn) 報(bào) 告 2010—2011第二學(xué)期 課程名稱: Java程序設(shè)計(jì)院系:計(jì)算機(jī)科學(xué)學(xué)院年級: 2009 專業(yè):計(jì)算機(jī)科學(xué)與技術(shù)大班 學(xué)號: 09061060 姓 名: 李亞巧 指...... 《面向?qū)ο蟪绦蛟O(shè)計(jì)》實(shí)驗(yàn)報(bào)告與習(xí)題冊 2013 / 2014 學(xué)年 第1學(xué)期 系 別 計(jì)算機(jī)科學(xué)與技術(shù)系 專 業(yè) 班 級 姓 名計(jì)算機(jī)軟件 軟件一班 羅曉薇朱強(qiáng) 指導(dǎo)教師 目 錄 實(shí)驗(yàn)......第二篇:Java實(shí)驗(yàn)報(bào)告
第三篇:JAVA實(shí)驗(yàn)報(bào)告
第四篇:JAVA實(shí)驗(yàn)報(bào)告
第五篇:java實(shí)驗(yàn)報(bào)告
聲明:本文內(nèi)容由互聯(lián)網(wǎng)用戶自發(fā)貢獻(xiàn)自行上傳,本網(wǎng)站不擁有所有權(quán),未作人工編輯處理,也不承擔(dān)相關(guān)法律責(zé)任。如果您發(fā)現(xiàn)有涉嫌版權(quán)的內(nèi)容,歡迎發(fā)送郵件至:645879355@qq.com 進(jìn)行舉報(bào),并提供相關(guān)證據(jù),工作人員會在5個工作日內(nèi)聯(lián)系你,一經(jīng)查實(shí),本站將立刻刪除涉嫌侵權(quán)內(nèi)容。 JAVA實(shí)驗(yàn)報(bào)告
JAVA聊天室實(shí)驗(yàn)報(bào)告
Java實(shí)驗(yàn)報(bào)告電子稿(匯編)
java實(shí)驗(yàn)報(bào)告4
java實(shí)驗(yàn)報(bào)告5范文合集
Java上機(jī)實(shí)驗(yàn)報(bào)告
java實(shí)驗(yàn)報(bào)告(精選五篇)
JAVA實(shí)驗(yàn)報(bào)告冊范文合集