久久99精品久久久久久琪琪,久久人人爽人人爽人人片亞洲,熟妇人妻无码中文字幕,亚洲精品无码久久久久久久

Java程序設計實驗報告[合集五篇]

時間:2019-05-12 07:36:55下載本文作者:會員上傳
簡介:寫寫幫文庫小編為你整理了多篇相關的《Java程序設計實驗報告》,但愿對你工作學習有幫助,當然你在寫寫幫文庫還可以找到更多《Java程序設計實驗報告》。

第一篇:Java程序設計實驗報告

Java程序設計實驗報告

實驗一

實驗題目:從鍵盤上讀入10個字符串存入數組a中,然后輸出這10個字符串中最大字符串和最小字符串。

實驗代碼:

public class StrPro {

public static void main(String[] args){

String str[] = new String[5];System.out.println(“Please input 10 strings:”);int i;String max,min;for(i=0;i<5;i++){

} max = str[0];min = str[0];for(i=0;i

}

}

} } if(min.compareTo(str[i])>0){ } min = str[i];System.out.println(“最大的字符串為:”+max);System.out.println(“最小的字符串為:”+min);實驗結果:

實驗心得體會:

掌握了java的基本語法,數組的定義與使用,做這個實驗要了解字符串數組的定義及字符串數組的輸入方法,還有比較字符串數組的大小的調用方法等。

實驗二

實驗題目:

自定義一個矩形類(Rectangle),包含的屬性有:長(length),寬(width),包含的方法有:關于屬性的setter和getter方法,即setLength,getLength,setWidth,getWidth,計算矩形面積的方法(getArea)。

定義矩形類的子類正方形類(Square),包含的屬性和方法自行確定,要求完成的功能是,能計算正方形的面積。

定義一個測試類(Test),測試矩形類和正方形類能否正確的計算面積。

以上類中屬性和方法的訪問權限自行確定,方法和構造方法若有參數,也自行確定。

實驗代碼:

public class Rectangle {

int Length;int Width;public int getLength(){ } public void setLength(int length){ } public int getWidth(){ return Width;Length = length;return Length;} public void setWidth(int width){

Width = width;} int getArea(){

return Length * Width;} }

public class Square extends Rectangle{ Square(int border){

super.setLength(border);

super.setWidth(border);} }

public class Test { public void test(){

System.out.println(“請選擇計算的形狀的序號:1.矩形

Scanner sc = new Scanner(System.in);

int i = sc.nextInt();int len,wid;2.正方形”);

} if(i==1){

} else if(i==2){

} System.out.print(“請輸入正方形的邊長:”);Scanner s = new Scanner(System.in);len = s.nextInt();Square sq = new Square(len);System.out.println(“正方形面積為:”+sq.getArea());System.out.print(“請輸入矩形的長:”);Scanner s = new Scanner(System.in);len = s.nextInt();System.out.print(“請輸入矩形的寬:”);wid = s.nextInt();Rectangle re = new Rectangle();re.setLength(len);re.setWidth(wid);System.out.println(“矩形面積為:”+re.getArea());else{ } System.out.println(“輸入錯誤!”);

} public static void main(String[] args){ } new Test().test();實驗結果:

實驗心得體會:

做這個實驗要掌握如何定義類以及類的成員變量、類的方法,學會對象的創建、對象屬性的引用和方法的調用以及如何定義和使用構造方法。掌握this的使用以及派生子類的方法,理解關鍵字super的含義。理解繼承中屬性的隱藏和方法的覆蓋機制,理解在繼承關系中構造方法的調用過程。

實驗三

實驗題目:定義一個Student類,包含姓名(name)、身高(height)、體重(weight),以及talk()方法,該方法的功能是,輸出自己的身高和體重信息。

Student類實現Comparable接口,實現按照體重的大小比較兩個Student對象的大小。最后,定義一個測試類,生成一個數組,該數組有6個元素,每個元素類型是Student,調用Arrays.sort方法對該數組排序。

實驗代碼:

public class Student implements Comparable {

public void setName(String name){ } this.name = name;public String getName(){ } return name;public Student(String name, float height, float weight){

} super();this.name = name;this.height = height;this.weight = weight;private String name;private float height, weight;

public float getHeight(){ } return height;public void setHeight(float height){ } this.height = height;public float getWeight(){ } return weight;public void setWeight(float weight){ } this.weight = weight;public void speak(){ System.out.println(“我是” + name + “,我的身高是” + height + “,我的體重是” + weight);

@Override }

} public int compareTo(Student o){

} int flag;if(this.weight

public String toString(){

} return “Person [name=” + name + “, height=” + height + “, weight=” + weight + “]”;public class Test { public static void main(String[] args){

}

} int i;Student ps[] = new Student[6];ps[0] = new Student(“張三”, 170, 110);ps[1] = new Student(“李四”, 168, 120);ps[2] = new Student(“王五”, 165, 115);ps[3] = new Student(“趙六”, 172, 121);ps[4] = new Student(“周七”, 160, 100);ps[5] = new Student(“鄭八”, 166, 119);System.out.println(“排序前數組元素的序列是:”);for(i = 0;i < ps.length;i++){ } Arrays.sort(ps);//調用Java系統類中的排序方法對ps數組排序 System.out.println(“n排序后數組元素的序列是:”);for(i = 0;i < ps.length;i++){ } System.out.println(ps[i]);ps[i].speak();實驗結果:

實驗心得體會:

本次實驗主要掌握對compareTo方法的重寫,當返回值為0的時候此方法調用會出現錯誤,導致不進行排序,需要特別注意。這個實驗主要使我們掌握了對類的接口的實現,和數組的比較,并使我們理解其中的細節。

第二篇:Java語言程序設計實驗報告1

《Java語言程序設計》實驗報告一

學生姓名: 孫文琳

班級: 信息111

學號:201152275119 實驗地點: 經管中心證券實驗室

指導教師:趙利平實驗日期:

2012.3.6

實驗環境:Windows 2000+JDK1.6

1.實驗目的(1)養成良好的編程風格;(2)掌握字符數據類型及其運算;

(3)熟悉從輸入對話框獲取輸入和從控制臺獲取輸入兩種方法;(4)掌握布爾運算符;(5)掌握分支語句if和switch。

2.實驗內容(1)在控制臺下求兩個實數的最大值:完成實驗教材P22程序清單2-2;(2)

3.實驗過程

報告撰寫具體要求:上述實驗內容要求寫出源代碼及運行結果。實驗內容(1)://CompareTwoNumbersl.java

import java.util.Scanner;

public class CompareTwoNumbers1{

double number1,number2;

Scanner scanner;

public CompareTwoNumbers1(){

System.out.println(“請輸入兩個數字:”);

scanner=new Scanner(System.in);

number1=scanner.nextDouble();

number2=scanner.nextDouble();

System.out.println(“較大的數是:”+(number1>number2?number1:number2));

}

public static void main(String args[]){ CompareTwoNumbers1 ct=new CompareTwoNumbers1();System.exit(0);}

}

實驗內容(2):

//DollarConvertor.java import java.util.Scanner;public class DollarConvertor{ public static void main(String args[]){ System.out.println(“請輸入美元數:”);Scanner scanner=new Scanner(System.in);double i=scanner.nextDouble();double result=i*6.2875;System.out.println(“對應的人民幣數:”+result);} }

實驗內容(3): public class MultiplyList1{ public static void main(String args[]){ String output=“";for(int row=1;row<=9;row++){ for(int col=1;col<=row;col++)output+=col+”*“+row+”=“+(row*col)+” “;output+=”n";} System.out.println(output);System.exit(0);}}

4.實驗總結

心得體會:做實驗要小心翼翼,注意Java大小區分

第三篇:Java猜拳小游戲程序設計實驗報告

Java程序設計實驗報告

班級:

學號:

姓名:

實驗題目:猜拳小游戲

實驗要求:

用java編寫一個人機對戰的猜拳小游戲。人選擇性出拳,電腦隨機出拳,判斷輸贏,記錄輸贏情況。有簡單的操作界面。

實驗內容:

1、問題分析過程:

(1)首先分析猜拳游戲本身的玩法:

人選擇性出拳,電腦隨機出拳,判斷輸贏,記錄輸贏情況。(2)用面向對象的思想來分析:

在游戲過程中有幾個對象組成人

電腦

游戲規則

抽象出3個類:Person、Computer、Game Person類有哪些屬性和行為呢?

屬性:名字name,輸贏次數(比分)score 行為:出拳ShowFirst()

選擇性

Computer類有哪些屬性和行為呢?

屬性:名字name,輸贏次數(比分)score 行為:出拳showFist()

隨機

Game類有哪些屬性和行為呢?

屬性:游戲的雙方(person、computer)、對戰局數count 行為:產生角色initial()、游戲規則startGame()、顯示比賽結果showResult()、統計

比賽結果calcResul()

2、主要實現代碼:

import java.util.*;public class StartGame { public static void main(String[]args){

Game start = new Game();//實例化游戲類

start.initial();//調用初始化方法

start.startGame();//調用游戲開始方法

start.showResult();//調用游戲結果顯示方法

} } import java.util.*;public class Person { String name;//名字屬性

int score;//積分屬性

//出拳方法

public int showFist(){

System.out.print(“n請出拳:1.剪刀2.石頭3.布(輸入相應數字):”);

Scanner input = new Scanner(System.in);

int num = input.nextInt();

String fist = “";//保存出拳

switch(num){ case 1:

fist = ”剪刀“;

break;

case 2:

fist = ”石頭“;

break;

case 3:

fist = ”布“;

break;

}

System.out.println(name + ”出拳:“ + fist);

return num;} } import java.util.*;public class Game { //Person person;

//甲方

//Computer computer;//乙方

int count;

//對戰次數

Person person = new Person();//實例化用戶類

Computer computer = new Computer();//實例化計算機類

//初始化方法

public int initial(){

count = 0;

return count;} //游戲開始方法

public void startGame(){

//顯示游戲開始界面

System.out.println(”---------------歡

System.out.println(“tt******************************”);

System.out.println(“tt**

^_^ 猜拳,Start ^_^

**”);

System.out.println(“tt*****************************”);

界--------------n“);

System.out.println(”nn出拳規則:1.剪刀 2.石頭 3.布“);//選擇計算機角色

System.out.print(”請選擇對方角色:1.劉備 2.孫權 3.曹操:“);Scanner input = new Scanner(System.in);int num = input.nextInt();switch(num){ case 1: computer.name = ”劉備“;break;case 2: computer.name = ”孫權“;break;case 3:

} computer.name = ”曹操“;break;//輸入用戶角色名

System.out.print(”請輸入你的姓名:“);person.name = input.next();

//顯示對戰雙方

System.out.print(person.name + ” VS “ + computer.name + ” 對戰n“);//開始游戲

System.out.print(”n要開始嗎?(y/n)“);String con = input.next();int perFist;//用戶出的拳 int compFist;//計算機出的拳

if(con.equals(”y“)){//判斷是否開始

String answer = ”y“;

while(”y“.equals(answer)){//循環條件是是否開始下一輪

//出拳

perFist = person.showFist();//調用用戶出拳方法

compFist = computer.showFist();//調用計算機出拳方法

//裁決

if((perFist == 1 && compFist == 1)||

(perFist == 2 && compFist == 2)||

(perFist == 3 && compFist == 3)){

System.out.println(”結果:和局,真衰!n“);//平局

}

else if((perFist == 1 && compFist == 3)||

(perFist == 2 && compFist == 1)||

(perFist == 3 && compFist == 2)){

System.out.println(”結果:恭喜, 你贏了!n“);//用戶贏

person.score++;

//累計用戶積分

}

else{

}

} System.out.println(”結果說:^_^,你輸了,真笨!n“);//計算機贏

computer.score++;

//累計計算機積分 } count++;//累計對戰次數

System.out.print(”是否開始下一輪(y/n):“);answer = input.next();}

//比較得分情況的方法 public void showResult(){ System.out.println(”-----------------------“);System.out.println(computer.name + ” VS “ + person.name);

System.out.println(”對戰次數:“ + count);System.out.println(”n姓名t得分n“ + person.name + ”t“ + person.score

+ ”n“ + computer.name + ”t“ + computer.score + ”n“);

//比較積分

if(computer.score == person.score){

System.out.println(”結果:打成平手,下次再和你一分高下!“);

}

else if(computer.score < person.score){

System.out.println(”結果:你果然是高手,“ + computer.name + ”佩服!“);

}

else{

System.out.println(”結果:呵呵,笨笨,下次加油哦!“);

}

System.out.println(”-----------------------“);} } public class Computer {

String name;//名字屬性 int score;//積分屬性 //出拳方法

public int showFist(){ int num =(int)(Math.random()*3)+ 1;String fist = ”“;switch(num){ case 1:

fist = ”剪刀“;

break;case 2:

fist = ”石頭“;

break;case 3:

fist = ”布“;

break;

}

System.out.println(name + ”出拳:" + fist);

return num;} } 運行界面:

3、實驗心得體會:

從本次課程設計的完成中,我發現我有很多不足的地方,最突出的是所掌握的知識太少,學到的知識應用不到實踐中。后來通過看書查找相關資料,完成課程設計任務。

程序設計語言是程序設計的工具,如果想有效的設計程序,正確的應用程序表達算法,必須準確應用程序設計語言;學習程序設計,必須要多讀程序,并試著自己編寫程序,多上機調試程序代碼。

第四篇:Java實驗報告

《Java簡易聊天室》

實驗目的:實現簡單的客服端與服務端通訊,進一步鞏固,加深對Java語言基礎知識的了解,將理論與實際相結合。

實驗要求:能相互之間發送消息,并進行簡單的異常處理。

聊天室截圖與說明:

客戶端

服務端

將客服端與服務端程序同時運行,此時會顯示出客戶端與服務端界面。在客戶端界面上點擊“連接”按鈕,即可使客戶端與服務端進程建立連接。在文本框中輸入將要發送的消息,點擊“發送”按鈕,即可將消息發送到對應端口。當服務端發送消息時,服務端便相當于客戶端。當需要終止連接時,關閉相應窗口即可。

設計概要:類/接口/函數說明

1.public class ClientUI extends Jframe{}

public class ServerUI extends Jframe{}

ClientUI與ServerUi繼承Frame類構建客戶端與服務器端窗口。

2.class ChatClient extends Thread{}

class SvrCom extends Thread{}

通訊類ChatClient/SvrCom負責守候數據到來

3.public void run()

用于監聽客戶端/服務器端發送來的信息,運行連接

4.public void sendMsg(String msg){// 用于發送信息

try {

out.println(“【客戶端】” + msg);

} catch(Exception e){

System.out.println(e);

}

} public void sendMsg(String msg){// 用于發送信息

try {

out.println(“【服務器】” + msg);// 把信息寫入輸出流

} catch(Exception e){

System.out.println(e);

} } 5.try {

msg = in.readLine();// 從in對象上讀數據信息

} 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);// 創建sc, 用服務器ip和端口作參數

System.out.println(”已順利聯接到服務器。“);

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);// 開設服務器端口6666

System.out.println(”啟動服務器成功,等待端口號: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();

自我評價或總結:經過本次實驗,進一步了解了客戶端與服務器之間的通信機制,對以后的編程實踐墊定了基礎。同時還鞏固了GUI圖形界面知識,更重要的是它使我對網絡編程有了一定的了解,也學到了不少知識。

附:

源代碼: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(”發送“);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(”服務器:“));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(”已順利聯接到服務器。“);

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.*;/** * 服務端界面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(”服務器端“);

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(”發送“);sendBtn.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent ae){

server.sendMsg(sendArea.getText());

mainArea.append(”【服務器】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(“啟動服務器成功,等待端口號: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(”【服務器】" + msg);} catch(Exception e){

System.out.println(e);} }

第五篇:JAVA實驗報告

學 生 實 驗 報 告 冊

(理工類)

課程名稱:面向對象程序設計 專業班級:16計算機科學與技術(專轉本)

學生學號: 1613203022 學生姓名: 張義丹

所屬院部: 計算機工程 指導教師: 劉 晶 16 ——20 17 學年 第 2 學期

金陵科技學院教務處制 實驗報告書寫要求

實驗報告上交電子稿,標題采用四號黑體,正文采用小四號宋體,單倍行距。

實驗報告書寫說明

實驗報告中實驗目的和要求、實驗儀器和設備、實驗內容與過程、實驗結果與分析這四項內容為必需項。教師可根據學科特點和實驗具體要求增加項目。

填寫注意事項

(1)細致觀察,及時、準確、如實記錄。(2)準確說明,層次清晰。

(3)盡量采用專用術語來說明事物。

(4)外文、符號、公式要準確,應使用統一規定的名詞和符號。(5)應獨立完成實驗報告的書寫,嚴禁抄襲、復印,一經發現,以零分論處。

實驗報告批改說明

實驗報告的批改要及時、認真、仔細,一律用紅色筆批改。實驗報告的批改成績采用五級記分制或百分制,按《金陵科技學院課堂教學實施細則》中作業批閱成績評定要求執行。

實驗項目名稱:Java編程基礎 實驗學時: 6 同組學生姓名: ———— 實驗地點: 工科樓A101 實驗日期: 17.3.21~17.4.4 實驗成績: 批改教師: 劉晶 批改時間:

實驗1 Java編程基礎

一、實驗目的和要求

(1)熟練掌握JDK1.6及Eclipse4.2編寫調試Java應用程序及Java小程序的方法;(2)熟練掌握Java應用程序的結構;

(3)了解Java語言的特點,基本語句、運算符及表達式的使用方法;(4)熟練掌握常見數據類型的使用;

(5)熟練掌握if-else、switch、while、do-while、for、continue、break、return語句的使用方法;

(6)熟練掌握數組和字符串的使用;

(7)調試程序要記錄調試過程中出現的問題及解決辦法;

(8)編寫程序要規范、正確,上機調試過程和結果要有記錄,不斷積累編程及調試經驗;

(9)做完實驗后給出本實驗的實驗報告。

二、實驗儀器和設備

奔騰以上計算機,Windows 操作系統,裝有JDK1.6和Eclipse4.2軟件。

三、實驗過程

(1)分別使用JDK命令行和Eclipse編譯運行Java應用程序;適當添加注釋信息,通過javadoc生成注釋文檔;為主方法傳遞參數“Hello world”字符串,并輸出,記錄操作過程。

public class Hello { public static void main(String args[]){ System.out.println(“Hello!”);} }(2)分別使用JDK命令行和Eclipse編譯Java Applet,并建立HTML文檔運行該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)根據變量score中存放的考試分數,輸出對應的等級。要求從鍵盤輸入學生成績,60分以下為D等;60~69為C等;70~89為B等;90~100為A等。(4)編寫一個Java Application程序,輸出區間[200,300]上的所有素數,將其用數組prime[]保存,并以每10個一行的形式顯示運行結果。(5)輸出下列數字形式,要求用二維數組完成。①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)求二維數組的鞍點,即該位置上的元素在該行上最大,在列上最小。也可能無鞍點。(7)分析下列程序的輸出結果,掌握equals()方法和“= =”的區別。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,立即退出循環:否則繼續比較,直到字符全部比較完,yes的值仍為true,才能肯定str是回文串。

算法二:將原串str反轉成temp串,再比較兩串,如果相等則是回文字符串。(9)使用String類的compareTo(String s)方法,對以下字符串從小到大排序:“melon”, “apple”, “pear”, “banana”,顯示輸出排序結果。

要求:

(1)編譯調試程序之前應配置好環境變量;

(2)要分別掌握用JDK命令行和Eclipse集成開發環境調試Java程序;(3)注意Java兩大類程序:應用程序和小程序的區別。

程序清單:

(建議程序中適當添加注釋信息,增強可讀性;較長程序可分欄書寫,保證報告排版整潔美觀。)

(1)主方法傳遞參數“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(“請輸入分數按回車”);

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(“數據錯誤”);

} } }(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] + “ ”);// 打印數據

}

}

} 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;//找到鞍點標記

int row=0;//第1行下標

int max=0;//記錄當前行最大值的列下標

while(!find && row

{

max=0;//初始設每行第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類,按字典序排列數組a:”);SortString.sort(a);System.out.println(“排序結果是:”);for(String s:a){ System.out.print(“ ”+s);} System.out.println(“");System.out.println(”使用類庫中的Arrays類,按字典序排列數組b:“);Arrays.sort(b);System.out.println(”排序結果是:“);for(String s:b){ System.out.print(” “+s);} }

四、實驗結果與分析(程序運行結果及其分析)

(1)

(2)

(3)

(4)

(5)

(6)

(7)

(8)

(9)

五、實驗體會(遇到問題及解決辦法,編程后的心得體會)

在這次實驗中,我知道了eclipse和jdk運行程序的區別,jdk比較麻煩一些,需要配置變量。在實驗中,配置jdk的環境變量要注意它的path和 classpath,如果classpath本身就有,可以在后面加分號,這樣不影響其它的classpath的使用。學會了如何生成注釋文檔,主函數傳遞參數的方法,還有壓縮文件,實驗中還對數組的創建和使用進行了練習,還有一些類的應用。

實驗項目名稱: 面向對象編程 實驗學時: 8 同組學生姓名: ———— 實驗地點: 工科樓A101 實驗日期: 17.4.11~17.5.2 實驗成績: 批改教師: 劉晶 批改時間:

實驗2 面向對象編程

一、實驗目的和要求

(1)熟練掌握Java語言類定義的基本語法;(2)熟練掌握類成員的訪問控制,對象建立的方法;(3)熟練掌握類構造方法、成員方法的定義和重載;(4)熟練掌握類繼承、多態和抽象性;(5)熟練掌握接口的定義和實現方法;(6)掌握基本的異常處理方法;

(7)調試程序要記錄調試過程中出現的問題及解決辦法;

(8)編寫程序要規范、正確,上機調試過程和結果要有記錄,不斷積累編程及調試經驗;

(9)做完實驗后給出本實驗的實驗報告。

二、實驗儀器和設備

奔騰以上計算機,Windows 操作系統,裝有JDK1.6和Eclipse4.2軟件。

三、實驗過程

(1)定義一個Man類,保存在Man.java文件中,類中包含說話方法如下: public class Man

{

public void say()

{

System.out.println(“我是中國人!”);

}

} 為此類打包為cn.edu.jit.chinese;再在Man.java文件所在路徑下,創建一個China.java文件,其中定義China類如下: public class China

{

public static void main(String[] args)

{

Man lihua = new Man();

lihua.say();

}

}

在China類中引用Man類,輸出顯示“我是中國人!”。試著去掉Man類的public修飾,看看會發生什么情況?

(2)設計復數類,成員變量包括實部和虛部,成員方法包括實現復數加法、減法、字符串描述、比較是否相等等操作。

(3)包的建立與使用:設計計算器類Calculator,計算加、減、乘、除和立方體體積,并且打包為mypackage。觀察源文件目錄下是否生成了mypackage文件夾,在該文件夾中是否有Calculate.class文件。編輯PackageDemo.java,保存在Calculator.java同一目錄下,引用計算器類的各方法顯示計算結果。

(4)試編碼實現簡單的銀行業務:處理簡單帳戶存取款、查詢。編寫銀行帳戶類BankAccount,包含數據成員:余額(balance)、利率(interest);操作方法:查詢余額、存款、取款、查詢利率、設置利率。再編寫主類UseAccount,包含main()方法,創建BankAccount類的對象,并完成相應操作。

(5)假定根據學生的3門學位課程的分數決定其是否可以拿到學位,對于本科生,如果3門課程的平均分數超過60分即表示通過,而對于研究生,則需要平均超過80分才能夠通過。根據上述要求,請完成以下Java類的設計: 1)設計一個基類Student描述學生的共同特征。

2)設計一個描述本科生的類Undergraduate,該類繼承并擴展Student類。3)設計一個描述研究生的類Graduate,該類繼承并擴展Student類。

4)設計一個測試類StudentDemo,分別創建本科生和研究生這兩個類的對象,并輸出相關信息。

(6)設計三角形類,繼承圖形抽象類,計算三角形面積和周長。

(7)試編碼實現多態在工資系統中的應用:給出一個根據雇員類型利用abstract方法和多態性完成工資單計算的程序。Employee是抽象類,Employee的子類有Boss(每星期發給他固定工資,而不計工作時間)、CommissionWorker(除基本工資外還根據銷售額發放浮動工資)、PieceWorker(按其生產的產品數發放工資)、HourlyWorker(根據工作時間長短發放工資)。該例的Employee的每個子類都聲明為final,因為不需要再繼承它們生成子類。在主測試類Test中測試各類雇員工資計算結果。

提示:對所有雇員類型都使用earnings()方法,但每個人掙的工資按他所屬的雇員類計算,所有雇員類都是從超類Employee派生出的。在超類中聲明earnings()為抽象方法,并且對于每個子類都提供恰當的earnings()的實現方法。為了計算雇員的工資,程序僅僅使用雇員對象的一個超類引用并調用earnings()方法。在一個實際的工資系統中,各種Employee對象的引用可以通過一個Employee引用數組來實現。程序依次使用數組的每個元素(Employee引用)調用每個對象的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)設計圓柱體類和圓椎體類,繼承圓類Circle并實現體積接口Volume,計算表面積和體積。

(9)定義一個接口CanFly,描述會飛的方法public void fly();分別定義飛機類和鳥類,實現CanFly接口。定義一個測試類,測試飛機和鳥。測試類中定義一個makeFly(CanFly obj)方法,讓會飛的事物飛起來(即調用相應類的fly()方法)。然后在main方法中創建飛機對象和鳥對象,并在main方法中調用makeFly(CanFly obj)方法,讓飛機和鳥起飛。

(10)異常的捕獲:計算兩數相除并輸出結果。使用三個catch子句,分別捕捉輸入輸出異常、除數為0的異常和參數輸入有誤異常。import java.io.*;class Ex1 { public static void main(String args[ ]){ try{ BufferedReader strin=new BufferedReader(new InputStreamReader(System.in));//建立輸入流緩沖區 System.out.print(”請輸入除數:“);String cl=strin.readLine();//鍵盤輸入 int a=Integer.parseInt(cl);System.out.print(”請輸入被除數:“);cl=strin.readLine();int b=Integer.parseInt(cl);int c=b/a;System.out.println(”商為:“+c);} //捕獲與I/O有關的異常(空白處補全捕獲語句)

//捕獲數值轉化時的異常,如不能將字符轉化成數值

//捕獲除數為0的異常

} } 編譯并運行,當產生輸入輸出異常時顯示異常信息;當輸入除數為0時,出現算術異常,提示除數為0,并要求重新輸入;當輸入的不是整數時,如將30輸成了3o,出現數值格式異常,提示輸入整數。

(11)編寫程序包含自定義異常MyException,當100被13和4除時拋出該異常,其余除數顯示商值。

要求:

(1)注意選用適當的類成員修飾符(private、protected、public等),比較它們的使用情況;

(2)養成良好的編程習慣,嚴格按照命名規則為包、類及類成員命名,將每個程序打包,包的命名方式如two.num1表示實驗二的第一題;

(3)學會使用Eclipse的各種調試方法;

(4)學會查閱Java API文檔,如查找異常類的使用方法。

程序清單:

(建議程序中適當添加注釋信息,增強可讀性;較長程序可分欄書寫,保證報告排版整潔美觀。)(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.*;//導入包

public class China { public static void main(String[] args){

Man lihua = new Man();//主方法先創建類然后調用類

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);//創建類,調用類里面的方法

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);//調用

} 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(”飛機借助螺旋槳飛上天空“);} } 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));//建立輸入流緩沖區

System.out.print(”請輸入除數:“);String cl=strin.readLine();//鍵盤輸入

int a=Integer.parseInt(cl);System.out.print(”請輸入被除數:“);cl=strin.readLine();int b=Integer.parseInt(cl);int c=b/a;System.out.println(”商為:“+c);} //捕獲與I/O有關的異常(空白處補全捕獲語句)

catch(IOException e){System.out.println(”輸入輸出異常“);} //捕獲數值轉化時的異常,如不能將字符轉化成數值

catch(NumberFormatException e){System.out.println(”數值格式異常,重新輸入“);

} //捕獲除數為0的異常

catch(ArithmeticException e){System.out.println(”除數為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(”請輸入實數除法運算的被除數:“);

String str = in.readLine();

double a = Double.parseDouble(str);

System.out.print(”請輸入除數:“);

str = in.readLine();

double b = Double.parseDouble(str);

System.out.println(”商結果:“+division(a,b));

}

catch(ArithmeticException e1){

System.out.println(”商結果:Infinity“+e1);

System.out.println(”商結果:NaN“+e1);

}

catch(NumberFormatException e2){

System.out.println(”異常:字符串不能轉換成整數!“+e2);

}

catch(IOException e3){

System.out.println(”異常:IO異常“+e3);

}

finally{

System.out.println(”程序結束!“);

} } static double division(double a,double b)throws MyException{

if(a==100 &&(b==4 || b==13))

throw new MyException(”不符規范“);

else return(a/b);} }

四、實驗結果與分析(程序運行結果及其分析)

(1)

去掉Man類的public修飾,程序運行不出來,提示缺少Man的公開方法。(2)

(3)

(4)

(5)

(6)

(7)

(8)

(9)

(10)

(11)

五、實驗體會(遇到問題及解決辦法,編程后的心得體會)

學習程序設計的基本目的就是培養描述實際問題的程序化解決方案的關鍵技能Java面向對象程序設計是一門實踐性比較強的課程在實際中我們必須把理論和實踐結合起來。在實驗中我們對照課本的知識然后進行實際的操作而后發現實際的運用比課本提到的要多很多理論總是來源于實踐我們必須在現有的理論的基礎上進行有效地實踐。而這次實驗也讓我看到了現在學習的一個很大弱點就是實踐的實踐往往很少。在現實社會中我們必須懂得實際的操作才能更好的服務于社會。所以我必須在以后的學習中多動手多實際操作爭取能在實踐中找到屬于自己新的感悟,終于在學習Java時達到了事半功倍的效果。

實驗項目名稱: 圖形用戶界面 實驗學時: 6 同組學生姓名: ———— 實驗地點: 工科樓A101 實驗日期: 17.5.9~17.5.23 實驗成績: 批改教師: 劉晶 批改時間:

實驗3 圖形用戶界面

一、實驗目的和要求

(1)掌握Swing組件的使用方法;

(2)熟練掌握Swing中常用布局管理器的使用方法;(3)掌握用戶界面動作與事件的處理程序的編寫方法;(4)熟練掌握構造用戶界面的方法和常見界面元素的使用;(5)熟練掌握Java繪圖的主要方法。

(6)調試程序要記錄調試過程中出現的問題及解決辦法;

(7)編寫程序要規范、正確,上機調試過程和結果要有記錄,不斷積累編程及調試經驗;

(8)做完實驗后給出本實驗的實驗報告。

二、實驗儀器和設備

奔騰以上計算機,Windows 操作系統,裝有JDK1.6和Eclipse4.2軟件。

三、實驗過程

1.計算器設計

2.整數進制轉換

將一個十進制整數分別轉換成二進制、八進制和十六進制整數。

3.模擬裁判評分。

設計如圖所示圖形界面,顯示n個裁判的評分,根據制定規則計算出最后得分。要求:圖形界面采用表格顯示裁判評分,隨裁判人數變化而變化;指定分數范圍,若超出,則異常處理;

得分規則有指定接口約定,由多個接口對象給出多種得分規則,如求平均數值,或去掉一個最高分和一個最低分后,再求平均值。

4.編譯運行下例,然后修改程序,當使用鼠標單擊后在另一位置重新繪制月亮。【例】 在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;//圓外切矩形左上角坐標 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());//設置為背景色 g.fillOval(x-20,y-20,diameter,diameter);//畫圓 } } 5.根據阿基米德螺線的極坐標方程:r=aθ畫出相應圖形。

要求:

(1)注意選用適當的布局管理器設計圖形用戶界面,比較它們的布局情況;

(2)養成良好的編程習慣,嚴格按照命名規則為包、類及類成員命名,將每個程序打包,包的命名方式如three.num1表示實驗三的第一題;(3)學會使用Eclipse的各種調試方法;

(4)學會查閱Java API文檔,如查找事件類的處理里方法。

程序清單:

(建議程序中適當添加注釋信息,增強可讀性;較長程序可分欄書寫,保證報告排版整潔美觀。)

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“,”負“,”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==”負“){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(”十進制整數轉換“);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(”十進制“));this.add(t1);t1.addActionListener(this);this.add(new Label(”二進制“));this.add(t2);this.add(new Label(”八進制“));this.add(t3);this.add(new Label(”十六進制“));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());//設置為背景色 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);} }}

四、實驗結果與分析(程序運行結果及其分析)

(分析每題采用的布局管理器、事件處理類和主要功能實現方法)1.2.3.4.38

5.五、實驗體會(遇到問題及解決辦法,編程后的心得體會)

這次實驗主要是對圖形用戶界面的設計,這里有鼠標觸發的事件,就要讓類實現MouseListener,在類里面實現MouseListener的方法,這里是選擇單擊時(mouseClicked()),這個方法,在方法體內用getX(),getY()方法來獲取當前坐標。

實驗項目名稱:Java高級編程 實驗學時: 4 同組學生姓名: ———— 實驗地點: 工科樓A101 實驗日期: 17.5.30~17.6.6 實驗成績: 批改教師: 劉晶 批改時間:

實驗4 Java高級編程

一、實驗目的和要求

(1)了解文件的概念和文件對象的創建方法;(2)掌握使用文件輸入輸出流讀寫文件的方法;(3)了解線程的基本概念和多線程程序設計的基本方法;(4)掌握數據庫連接的方法;

(5)創建SQL查詢并更新數據庫中的信息;

(6)調試程序要記錄調試過程中出現的問題及解決辦法;

(7)編寫程序要規范、正確,上機調試過程和結果要有記錄,不斷積累編程及調試經驗;

(8)做完實驗后給出本實驗的實驗報告。

二、實驗儀器和設備

奔騰以上計算機,Windows 操作系統,裝有JDK1.6和Eclipse4.2軟件,MySQL數據庫。

三、實驗過程

(1)使用文件字節輸入/輸出流,合并兩個指定文件;當文件中的數據已排序時,合并后的數據也要求是已排序的。

(2)將Java的關鍵字保存在一個文本文件中,判斷一個字符串是否為Java的關鍵字。(3)編寫在構造方法中產生一個1-5之間的隨機數的繼承Thread類的線程類DelayPrintThread,使得線程體每休眠此隨機數時間就打印輸出線程號和休眠時間;另外編寫應用DelayPrintThread類的Java應用程序TwoThread.java,在main()方法中創建兩個線程,并應用sleep()控制主應用程序延遲一段時間。

(4)編寫繼承Runnable接口的Applet多線程小程序類MultiThreadApplet,編寫繼承該類的Applet小程序類Clock,在Clock中重新構造父類的run()方法,實現數字時鐘的功能,要求不斷刷新顯示時、分、秒。

(5)為學生信息表stuinfo設計數據庫應用程序,包括數據的輸入、刪除和查詢功能。

要求:

(1)注意選用適當的文件流進行文件讀寫;

(2)學會兩種創建線程的方法,并比較使用場合;

(3)養成良好的編程習慣,嚴格按照命名規則為包、類及類成員命名,將每個程序打包,包的命名方式如four.num1表示實驗四的第一題;(4)學會查閱Java API文檔,如查找常用工具類。

程序清單:

(建議程序中適當添加注釋信息,增強可讀性;較長程序可分欄書寫,保證報告排版整潔美觀。)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關鍵字有“+”:“);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中的關鍵字“);break;}

else continue;if(j==s.length)System.out.println(s1[i]+”不是java中的關鍵字“);} } 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+”:“+”休眠時間“+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時 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(”沒有數據“);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(”沒有數據");} }

四、實驗結果與分析(程序運行結果及其分析)1.45

2.3.4.五、實驗體會(遇到問題及解決辦法,編程后的心得體會)

通過這次實驗,我基本能夠理解線程的運行了,學會調用Thread類中的系統函數以及掌握這些函數的作用是難點,start()是開辟一條新線程。子類重寫父類的run()方法,里面用sleep,來控制每個線程的休眠時間,但是得注意這里應該要用try-catch語句來捕獲中斷異常。

下載Java程序設計實驗報告[合集五篇]word格式文檔
下載Java程序設計實驗報告[合集五篇].doc
將本文檔下載到自己電腦,方便修改和收藏,請勿使用迅雷等下載。
點此處下載文檔

文檔為doc格式


聲明:本文內容由互聯網用戶自發貢獻自行上傳,本網站不擁有所有權,未作人工編輯處理,也不承擔相關法律責任。如果您發現有涉嫌版權的內容,歡迎發送郵件至:645879355@qq.com 進行舉報,并提供相關證據,工作人員會在5個工作日內聯系你,一經查實,本站將立刻刪除涉嫌侵權內容。

相關范文推薦

    JAVA實驗報告

    河北北方學院信息科學與工程學院 《Java程序設計》 實 驗 報 告 實驗學期 2014 至 2015 學年 第 2 學期 學生所在系部 信息科學與工程學院 年級 2012 專業班級 電子三班 學......

    java實驗報告

    學 生 實 驗 報 告 冊 2013——2014學年第1學期 項目名稱: Java Web 學院: 信電 班級:11計算機科學與技術一班 學號: 155140007 姓名: 伍振東 指導教師: 李竹林 完成時間: 2013/9/2......

    JAVA實驗報告

    實驗報告一、 實驗目的 鞏固復習課上所講內容,進一步熟悉面向對象編程。 二、 實驗內容 編寫程序求點到原點的距離三、 程序清單及運行結果 abstractclass Distance { abstra......

    java程序設計教案

    《Java程序設計》 授 課 人:授課班級:電子商務專業 授課教案 第一章Java語言簡介 教學目的要求 ? 了解Java的基本特點和用途 ? 掌握如何下載Java SDK軟件包 ? 了解設置Java程序......

    Java程序設計教案

    Java程序設計 第一講 緒論 一、安裝netbean系統 二、hello world 典型程序結構中各部分的說明: /* * To change this template, choose Tools | Templates * and open the......

    java培訓-Java程序設計

    Java程序設計:圖形與多媒體處理(1) 本文主要介紹了Java的圖形設計以及多媒體處理,源碼作者也做了詳細的注釋,對于初學者應該不難。詳細請看下文 同心圓效果圖: 1. /** 2. *......

    java程序設計教案(★)

    課程教案 (理論教學) 課程名稱: Java程序設計 課程類型:( 2 )1、必修;2、選修;3、其它 授課對象: 專業(本科) 級 班 授課時間: 至 學年第 學期 計劃學時: 學時(其中:理論 ,實驗: ) 任課教師......

    Java程序設計報告

    楚雄師范學院 2015年春季期末Java程序設計報告 項目名稱:基于Java平臺開發的五子棋程序設計 學 院: 物理與電子科學學院 專 業:電子信息科學與技術 班 級:2 0 1 3 級 電 信 一......

主站蜘蛛池模板: 国产亚洲精品久久久久久久久| 成人精品一区二区三区在线观看| 日产日韩亚洲欧美综合在线| 国产精品三级av及在线观看| 亚洲国产精品久久一线app| 久久综合狠狠综合久久| 欧洲国产在线精品三区| 偷偷做久久久久免费网站| 欧美性性性性性色大片免费的| 67194熟妇人妻欧美日韩| 国产日产欧产精品精品软件| 国产性一交一乱一伦一色一情| 久久久久麻豆v国产精华液好用吗| 99热精品毛片全部国产无缓冲| 成人片黄网站色大片免费观看cn| 久久五月丁香合缴情网| 人妻另类 专区 欧美 制服| 熟女人妻在线视频| 欧美两根一起进3p做受视频| 久久亚洲精品无码爱剪辑| a级毛片免费观看在线| 69精品丰满人妻无码视频a片| 亚洲aⅴ永久无码一区二区三区| 97精品人人妻人人| 国产精品久久久久久久久绿色| 大学生粉嫩无套流白浆| 1000部拍拍拍18勿入免费视频下载| 亚洲人成网站18禁止| 久久棈精品久久久久久噜噜| 1000部啪啪未满十八勿入下载| 亚洲精品无码久久久久久久| 国产一卡2卡3卡四卡精品网站| 精品成人| 亚洲精品久久久久久久久久吃药| 蜜臀av色欲a片无码一区| 色一乱一伦一图一区二区精品| 两性色午夜免费视频| 国产福利无码一区在线| 欧美亅性猛交内射| 精品国产一区av天美传媒| 精品国产一区二区三区四区精华液|