java实验报告4

第一篇:java实验报告4
实验报告_实验4 常用类(学生学号_姓名)
一、实验目的
1.掌握String类的基本构造方法和常用方法的使用;
2.熟悉StringBuffer类的追加、插入、查找、替换、删除等操作; 3.熟悉Math类常量及常用方法的调用;
4.熟悉包装类的功能、重要属性、主要构造器和常用方法; 5.了解StringTokenizer类的一般使用。
二、实验内容与步骤
1、(基础题)运行下列程序,并回答问题:
(1)对于String对象来说,“==”运算符与equals()方法的功能有什么不同?
“==”运算符比较两个字符串引用是否指向同一个对象。equals()方法在于比较两个字符串的内容是否完全相同。
(2)s1和s2是否指向同一对象?为什么?
是,因为s1和s2是字符串常量,如果用户创建了一个字符串常量,系统首先会在字符串池中查找有无相同内容的字符串存在,若有就把原有取出使用,若无则重新生成,故s1和s2指向同一对象。
(3)s3和s4是否指向同一对象?为什么?
不是,用构造器生成的字符串对象,它会在堆中生成一个对象,很明显s3和s4指向了不同的对象。
(4)s1==s3是否成立?为什么?
不成立,“==”运算符比较两个字符串引用是否指向同一个对象。很明显s1和s3指向了不同的对象。
(5)s1、s2、s3、s4的内容是否相同?
是(6)compareTo()方法的功能是什么?当比较结果分别为 负数、正数、0 时,代表什么含义? Str1.compareTo(Str2);其返回的是一个int类型值。若Str1等于参数字符串Str2字符串,则返回0;若该Str1按字典顺序小于参数字符串Str2,则返回值小于0;若Str1按字典顺序大于参数字符串Str2,则返回值大于0。
2、(基础题)根据程序注释,将所缺代码补充完整,然后运行程序:
程序所缺代码: String str = new String(“zhangsan@scse.com.cn”);System.out.println(“字符串的长度: ” + str.length());// 输出字符串的长度 System.out.println(“字符串的首字符: ” + str.charAt(0));// 输出字符串的首字符
System.out.println(“字符'@'的索引号(即下标): ” + str.indexOf('@'));
System.out.println(“该邮箱的顶级域名(即最后一个单词): ” + str.substring(str.lastIndexOf('.')+1));
System.out.println(“字符串全部以大写方式输出为: ” + str.toUpperCase());
3、(基础题)根据程序注释,将所缺代码补充完整,再运行程序:: 程序所缺代码
StringBuffer sb= new StringBuffer(“里约热内卢奥运会举行时间:”);
sb.append(“8月8日晚8点”);
sb.replace(n, n+5,“第31届”);// 将字符串中“里约热内卢”替换为“第31届”
System.out.println(“字符串的长度为: ”+ sb.length());// 输出字符串的长度
sb.delete(12,25);// 删除字符串中从第12个字符开始到第25个字符为止的内容 // 在sb尾部追加“8月8日晚8点”字符串
sb.insert(sb.length()-1,” 8月5日-21日”);//在sb尾部追加“8月5日-21日”字符串
第二篇: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(”商结果:“+pision(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 pision(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(”
java实验报告4
本文2025-01-31 15:05:17发表“合同范文”栏目。
本文链接:https://www.wnwk.com/article/751700.html
- 二年级数学下册其中检测卷二年级数学下册其中检测卷附答案#期中测试卷.pdf
- 二年级数学下册期末质检卷(苏教版)二年级数学下册期末质检卷(苏教版)#期末复习 #期末测试卷 #二年级数学 #二年级数学下册#关注我持续更新小学知识.pdf
- 二年级数学下册期末混合运算专项练习二年级数学下册期末混合运算专项练习#二年级#二年级数学下册#关注我持续更新小学知识 #知识分享 #家长收藏孩子受益.pdf
- 二年级数学下册年月日三类周期问题解题方法二年级数学下册年月日三类周期问题解题方法#二年级#二年级数学下册#知识分享 #关注我持续更新小学知识 #家长收藏孩子受益.pdf
- 二年级数学下册解决问题专项训练二年级数学下册解决问题专项训练#专项训练#解决问题#二年级#二年级数学下册#知识分享.pdf
- 二年级数学下册还原问题二年级数学下册还原问题#二年级#二年级数学#关注我持续更新小学知识 #知识分享 #家长收藏孩子受益.pdf
- 二年级数学下册第六单元考试卷家长打印出来给孩子测试测试争取拿到高分!#小学二年级试卷分享 #二年级第六单考试数学 #第六单考试#二年级数学下册.pdf
- 二年级数学下册必背顺口溜口诀汇总二年级数学下册必背顺口溜口诀汇总#二年级#二年级数学下册 #知识分享 #家长收藏孩子受益 #关注我持续更新小学知识.pdf
- 二年级数学下册《重点难点思维题》两大问题解决技巧和方法巧算星期几解决周期问题还原问题强化思维训练老师精心整理家长可以打印出来给孩子练习#家长收藏孩子受益 #学霸秘籍 #思维训练 #二年级 #知识点总结.pdf
- 二年级数学下册 必背公式大全寒假提前背一背开学更轻松#二年级 #二年级数学 #二年级数学下册 #寒假充电计划 #公式.pdf


