****大学

《Java程序设计》

实验指导书

编者:王* 潘** 肖* 杨**

主审:刘**

********学院信息科学系

2013年1月9日

前  言

《Java 程序设计实验指导书》是电子信息科学与技术、信息管理与信息系统、物联网工程的一门编程语言专业课,主要介绍程序开发语言、产品配置环境和数据操作等这3种专业技能紧密结合方面的内容。

本书共分十个实验项目,每个实验项目分别包含三个具体的实验内容,系统地介绍了Java环境、基本数据类型与控制语句、类、对象、继承、字符串类、时间类、数字类、组件与事件处理、多线程、输入输出流和网络编程等内容。全书附有实验模板和实验思考题,学生可参考实验模板完成实验内容,配合实验思考题深入理解各部分实验。

本书作为实验指导书使用时,实验教学18~24学时,教师可根据实际教学情况进行调整。

本书由王*、潘**、肖*、杨**共同编写完成。由于作者水平有限,书中难免存在疏漏之处,敬请广大读者批评指正。

编者

2012年12月

目  录

实验项目一  Java环境演练 1

实验项目二  Java基本数据类型与控制语句 5

实验项目三  类与对象 11

实验项目四  继承与接口 20

实验项目五  字符串、时间与数字类 27

实验项目六  组件与事件处理(1) 32

实验项目七  组件与事件处理(2) 43

实验项目八  多线程 56

实验项目九  输入输出流 66

实验项目十  网络编程 76

部分参考代码 86

参考文献 93

《Java程序设计》

实验项目一  Java环境演练

一、实验目的

1.安装并配置Java运行开发环境;

2.掌握开发Java应用程序的3个步骤:编写源文件、编译源文件和运行应用程序;

3.掌握开发Java Applet程序的3个步骤:编写源文件、编译源文件和运行Java Applet程序;

4. 学习同时编译多个Java源文件。

二、实验内容

实验1.一个简单的应用程序

  • 实验要求:

编写一个简单的Java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习Java”和“We are students”。

  • 实验效果:
  • 图1-1 一个简单的应用程序
  • 程序模板:
 Hello.javapublic class Hello{     public static void main (String args[ ]){【代码1】    //命令行窗口输出"你好,很高兴学习Java"A a=new A();a.fA();}}class A{void fA(){【代码2】    //命令行窗口输出"We are students"}}
  • 实验后的练习:
  1. 编译器怎样提示丢失大括号的错误?
  2. 编译器怎样提示语句丢失分号的错误?
  3. 编译器怎样提示将System写成system这一错误?
  4. 编译器怎样提示将String写成string这一错误?

实验2.一个简单的Java Applet程序

  • 实验要求:

编写一个简单的Java Applet程序,并在Java Applet中写两行文字:“这是一个Java Applet程序”和“我改变了字体”。

  • 实验效果:
  • 图1-2 一个简单的Java Applet程序
  • 程序模板
FirstApplet.javaimport java.applet.*;import java.awt.*;public class FirstApplet extends Applet{  public void paint(Graphics g){g.setColor(Color.blue);   【代码1】//在Java Applet中绘制一行文字:“这是一个Java Applet 程序”g.setColor(Color.red);g.setFont(new Font("宋体",Font.BOLD,36));【代码2】//在Java Applet中绘制一行文字:“我改变了字体”}}
  • 实验后的练习:
  1. 程序中的主类如果不用public修饰,编译能通过吗?
  2. 程序中的主类如果不用public修饰,程序能正确运行吗?
  3. 程序将paint方法误写成Paint,编译能通过么?
  4. 程序将paint方法误写成Paint,运行时能看到有关的输出信息吗?

实验3.联合编译

  • 实验要求:

编写4个源文件:MainClass.java、A.java、B.java和C.java,每个源文件只有一个类,MainClass.java是一个应用程序(含有main方法),使用了A、B和C类。将4个源文件保存到同一目录中,例如:C:\100,然后编译Hello.java。

  • 实验效果:
  • 图1-3 联合编译
  • 程序模板
模板1:MainClass.javapublic class MainClass{     public static void main (String args[ ]){【代码1】    //命令行窗口输出"你好,只需编译我"A a=new A();a.fA();B b=new B();b.fB();}}模板2 :A.javapublic class A{void fA(){【代码2】    //命令行窗口输出"I am A"}}模板3 :B.javapublic class B{void fB(){【代码3】    //命令行窗口输出"I am B"}}模板4 :C.javapublic class C{void fC(){【代码4】    //命令行窗口输出"I am C"}}
  • 实验后的练习:
  1. 将Hello.java编译通过后,不断修改A.java源文件中的代码,比如,在命令行窗口输出“我是A类”或“我被修改了”。要求每次修改A.java源文件后,单独编译A.java,然后直接运行应用程序Hello。
  2. 如果需要编译某个目录下的全部Java源文件,比如C:\1000目录,可以使用如下命令:c:\1000\javac *.java

《Java程序设计》

实验项目二  Java基本数据类型与控制语句

一、实验目的

1.掌握char型数据和int型数据之间的相互转换,同时了解unicode字符表;

2. 掌握使用if…else if多分支语句;

3. 使用if…else分支和while循环语句解决问题。

二、实验内容

实验1.输出希腊字母表

  • 实验要求:

编写一个Java应用程序,该程序在命令行窗口输出希腊字母表。

  • 实验效果:
  • 图2-1 输出希腊字母表
  • 程序模板
GreekAlphabet.javapublic class GreekAlphabet{     public static void main (String args[ ]){int startPosition=0,endPosition=0;char cStart='α',cEnd='ω';【代码1】   //cStart做int型转换据运算,并将结果赋值给startPosition【代码2】   //cEnd做int型转换运算,并将结果赋值给endPosition   System.out.println("希腊字母\'α\'在unicode表中的顺序位置:"+(int)cStart);System.out.println("希腊字母表:");for(int i=startPosition;i<=endPosition;i++){char c='\0';【代码3】  //i做char型转换运算,并将结果赋值给cSystem.out.print(" "+c);if((i-startPosition+1)%10==0)System.out.println("");  }       }}
  • 实验后的练习:
  1. 将一个double型数据直接赋值给float型变量,程序编译时提示怎样的错误?
  2. 在应用程序的main方法中增加语句:

float x=0.618;

程序能编译通过么?

  1. 在应用程序的main方法中增加语句:

byte y=128;

程序能编译通过么?

  1. 在应用程序的main方法中增加语句:

int z=(byte)128;

程序输出变量z的值是多少?

实验2.回文数

  • 实验要求:

编写一个Java应用程序。用户从键盘输入一个1—9999之间的数,程序将判断这个数是几位数,并判断这个数是否是回文数。回文数是指将该数含有的数字逆序排列后得到的数和原数相同,例如12121、3223都是回文数。

  • 实验效果:
  • 图2-2 回文数

输入12321得到如下实验结果:

12321是5位数

12321不是回文数

  • 程序模板
Number.javaimport javax.swing.JOptionPane;public class Number{  public static void main(String args[]){int number=0,d5,d4,d3,d2,d1;String str=JOptionPane.showInputDialog("输入一个1至99999之间的数");number=Integer.parseInt(str);if(【代码1】) //判断number在1至99999之间的条件{【代码2】   //计算number的最高位(万位)d5【代码3】   //计算number的千位d4【代码4】   //计算number的百位d3d2=number%100/10;d1=number%10;if(【代码5】)  //判断number是5位数的条件{System.out.println(number+"是5位数");if(【代码6】) //判断number是回文数的条件{System.out.println(number+"是回文数");}else{System.out.println(number+"不是回文数");}}else if(【代码7】)  //判断number是4位数的条件{System.out.println(number+"是4位数");if(【代码8】) //判断number是回文数的条件码{System.out.println(number+"是回文数");}else{System.out.println(number+"不是回文数");}}else if(【代码9】)  //判断number是3位数的条件{System.out.println(number+"是3位数");if(【代码10】) //判断number是回文数的条件{System.out.println(number+"是回文数");}else{System.out.println(number+"不是回文数");}}else if(d2!=0){System.out.println(number+"是2位数");if(d1==d2){System.out.println(number+"是回文数");}else{System.out.println(number+"不是回文数");}}else if(d1!=0){System.out.println(number+"是1位数");System.out.println(number+"是回文数");}}else{System.out.printf("\n%d不在1至99999之间",number);}}}
  • 实验后的练习:
  1. 程序运行时,用户从键盘输入2332,程序提示怎样的信息?
  2. 程序运行时,用户从键盘输入654321,程序提示怎样的信息?
  3. 程序运行时,用户从键盘输入33321,程序提示怎样的信息?

实验3.猜数字游戏

  • 实验要求:

编写一个Java应用程序,实现下列功能:

    1. 程序随机分配给客户一个1—100之间的整数
    2. 用户在输入对话框中输入自己的猜测
    3. 程序返回提示信息,提示信息分别是:“猜大了”、“猜小了”和“猜对了”。
    4. 用户可根据提示信息再次输入猜测,直到提示信息是“猜对了”。
  • 实验效果:
  • 2-3 猜数字游戏
  • 程序模板

GuessNumber.java

import javax.swing.JOptionPane;

public class GuessNumber

{

public static void main (String args[ ])

{

System.out.println("给你一个1至100之间的整数,请猜测这个数");

int realNumber=(int)(Math.random()*100)+1;

int yourGuess=0;

String str=JOptionPane.showInputDialog("输入您的猜测:");

yourGuess=Integer.parseInt(str);

while(【代码1】) //循环条件

{

if(【代码2】) //条件代码

{

str=JOptionPane.showInputDialog("猜大了,再输入你的猜测:");

yourGuess=Integer.parseInt(str);

}

else if(【代码3】) //条件代码

{

str=JOptionPane.showInputDialog("猜小了,再输入你的猜测:");

yourGuess=Integer.parseInt(str);

}

}

System.out.println("猜对了!");

}

}

  • 实验后的练习:

1. 用“yourGuess>realNumber”替换【代码1】,可以么?

2. 语句:“System.out.println(“猜对了!”);”为何要放在while循环语句之后?放在while语句的循环体中合理吗?

《Java程序设计》

实验项目三  类与对象

一、实验目的

1. 使用类来封装对象的属性和功能;

2. 掌握类变量与实例变量,以及类方法与实例方法的区别;

3. 掌握使用package和import语句。

4. 巩固以下概念:

子类的继承性

子类对象的创建过程

成员变量的继承与隐藏

方法的继承与重写

二、实验内容

实验1.三角形、梯形和圆形的类封装

  • 实验要求:

编写一个Java应用程序,该程序中有3个类:Trangle、Leder和Circle,分别用来刻画“三角形”、“梯形”和“圆形”。具体要求如下:

a) Trangle类具有类型为double的三个边,以及周长、面积属性,Trangle类具有返回周长、面积以及修改三个边的功能。另外,Trangle类还具有一个boolean型的属性,该属性用来判断三个属能否构成一个三角形。

b) Lader类具有类型double的上底、下底、高、面积属性,具有返回面积的功能。

c) Circle类具有类型为double的半径、周长和面积属性,具有返回周长、面积的功能。

  • 实验效果:

梯形的面积:35.0

不是一个三角形,不能计算面积

三角形的面积:0.0

不是一个三角形,不能计算周长

三角形的周长:0.0

  • 程序模板:

AreaAndLength.java

class Trangle

{

double sideA,sideB,sideC,area,length;

boolean boo;

public  Trangle(double a,double b,double c)

{

【代码1】 //参数a,b,c分别赋值给sideA,sideB,sideC

if(【代码2】) //a,b,c构成三角形的条件表达式

{

【代码3】 //给boo赋值。

}

else

{

【代码4】 //给boo赋值。

}

}

double getLength()

{

【代码5】 //方法体,要求计算出length的值并返回

}

public double  getArea()

{

if(boo)

{

double p=(sideA+sideB+sideC)/2.0;

area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC)) ;

return area;

}

else

{

System.out.println("不是一个三角形,不能计算面积");

return 0;

}

}

public void setABC(double a,double b,double c)

{

【代码6】 //参数a,b,c分别赋值给sideA,sideB,sideC

if(【代码7】) //a,b,c构成三角形的条件表达式

{

【代码8】 //给boo赋值。

}

else

{

【代码9】 //给boo赋值。

}

}

}

class Lader

{

double above,bottom,height,area;

Lader(double a,double b,double h)

{

【代码10】 //方法体,将参数a,b,c分别赋值给above,bottom,height

}

double getArea()

{

【代码11】 //方法体,,要求计算出area返回

}

}

class Circle

{

double radius,area;

Circle(double r)

{

【代码12】 //方法体

}

double getArea()

{

【代码13】 //方法体,要求计算出area返回

}

double getLength()

{

【代码14】 //getArea方法体的代码,要求计算出length返回

}

void setRadius(double newRadius)

{

radius=newRadius;

}

double getRadius()

{

return radius;

}

}

public class AreaAndLength

{

public static void main(String args[])

{

double length,area;

Circle circle=null;

Trangle trangle;

Lader lader;

【代码15】 //创建对象circle

【代码16】 //创建对象trangle。

【代码17】 //创建对象lader

【代码18】 // circle调用方法返回周长并赋值给length

System.out.println("圆的周长:"+length);

【代码19】 // circle调用方法返回面积并赋值给area

System.out.println("圆的面积:"+area);

【代码20】 // trangle调用方法返回周长并赋值给length

System.out.println("三角形的周长:"+length);

【代码21】 // trangle调用方法返回面积并赋值给area

System.out.println("三角形的面积:"+area);

【代码22】 // lader调用方法返回面积并赋值给area

System.out.println("梯形的面积:"+area);

【代码23】

// trangle调用方法设置三个边,要求将三个边修改为12,34,1。

【代码24】 // trangle调用方法返回面积并赋值给area

System.out.println("三角形的面积:"+area);

【代码25】 // trangle调用方法返回周长并赋值给length

System.out.println("三角形的周长:"+length);

}

}

  • 实验后的练习:

1. 程序中仅仅省略【代码15】,编译能通过吗?

2. 程序中仅仅省略【代码16】,编译能通过吗?

3. 程序中仅仅省略【代码15】,运行时出现怎样的异常提示?

  1. 给Trangle类增加3个方法,分别用来返回3个边:sideA、sideB和sideC。
  2. 让AreaAndLength类中的circle对象调用方法修改半径,然后输出修改后的半径以及修改半径后的圆的面积和周长。

实验2.实例成员与类成员

  • 实验要求:

按程序模板的要求编写源文件,要特别注意程序的输出结果,并能正确解释输出的结果。

  • 实验效果:

100.0

200.0

300.0

150.0

300.0

  • 程序模板

Example.java

class A

{

【代码1】             //声明一个float型实例变量a

【代码2】             //声明一个float型类变量b,即static变量b

void setA(float a)

{

【代码3】        //将参数a的值赋值给成员变量a

}

void setB(float b)

{

【代码4】       //将参数b的值赋值给成员变量b

}

float getA()

{

return a;

}

float getB()

{

return b;

}

void inputA()

{

System.out.println(a);

}

static void inputB()

{

System.out.println(b);

}

}

public class Example

{

public static void main(String args[])

{

【代码5】            //通过类名操作类变量b,并赋值100

【代码6】            //通过类名调用方法inputB()

A cat=new A();

A dog=new A();

【代码7】    //cat象调用方法setA(int a)将cat的成员a的值设置为200

【代码8】    //cat调用方法setB(int b)将cat的成员b的值设置为400

【代码9】  //dog象调用方法setA(int a)将dog的成员a的值设置为150

【代码10】   //dog调用方法setB(int b)将dog的成员b的值设置为300

【代码11】   //cat调用inputA()。

【代码12】   //cat调用inputB()。

【代码13】   //dog调用inputA()。

【代码14】   //dog调用inputB()。

}

}

  • 实验后的练习:

1. 将inputA()方法中的

System.out.println(a);

改写为

System.out.println(a+b);

编译是否出错?为什么?

2. 将inputB()方法中的

System.out.println(b);

改写为

System.out.println(a+b);

编译是否报错?为什么?

实验3.使用package语句与import语句

  • 实验要求:

按实验要求使用package语句,并用import语句使用Java平台提供的包中的类以及自定义包中的类。掌握一些重要的操作步骤。

  • 程序模板:

模板1:

将模板1给出的Java源文件命名为SquareEquation.java,将编译后得到的字节码文件复制到c:\1000\tom\jiafei目录中。

SquareEquation.java

package tom.jiafei;

public class SquareEquation

{

double a,b,c;

double root1,root2;

boolean boo;

public  SquareEquation(double a,double b,double c)

{

this.a=a;

this.b=b;

this.c=c;

if(a!=0)

{

boo=true;

}

else

{

boo=false;

}

}

public void  getRoots()

{

if(boo)

{

System.out.println("是一元2次方程");

double disk=b*b-4*a*c;

if(disk>=0)

{

root1=(-b+Math.sqrt(disk))/(2*a);

root2=(-b-Math.sqrt(disk))/(2*a);

System.out.printf("方程的根:%f,%f\n",root1,root2);

}

else

{

System.out.printf("方程没有实根\n");

}

}

else

{

System.out.println("不是一元2次方程");

}

}

public void setCoefficient(double a,double b,double c)

{

this.a=a;

this.b=b;

this.c=c;

if(a!=0)

{

boo=true;

}

else

{

boo=false;

}

}

}

模板2:

将模板2给出的Java源程序SunRise.java保存到d:\2000中。在编译模板2给出的Java源文件之前,要重新设置classpath。假设本地机SDK的安装目录是E:\jdk1.5。

在命令行执行如下命令:

set classpath=e:\jdk1.5\jre\lib\rt.jar;.;c:\1000

然后编译模板2给出的Java源程序。或用鼠标右键点击“我的电脑”,弹出快捷菜单,然后选择“属性”命令,弹出“系统属性”对话框,再单击该对话框中的“高级”选项卡,然后单击“环境变量”按钮。将classpath的值修改为:

E:\jdk1.5\jre\lib\rt.jar;.;c:\1000

然后重新打开一个命令行窗口,编译模板2给出的Java源程序。

SunRise.java

import tom.jiafei.*;

class SunRise

{

public static void main(String args[ ])

{

SquareEquation equation=new SquareEquation(4,5,1);

equation.getRoots();

equation.setCoefficient(-3,4,5);

equation.getRoots();

}

}

  • 实验后的练习:

假设SDK的安装目录是E:\jdk1.5,那么Java运行系统默认classpath的值是:E:\jdk1.5\jre\lib\rt.jar;.;

其中的“”表示应用程序可以使用当前目录中的无名包类以及当前目录下的子目录中的类,子目录中的类必须有包名,而且包名要和子目录结构相对应。

因此,如果将模板2应用程序Sunrise.java的字节码文件存放到d:\5000中,并将SquareEquation.java的字节码文件存放在D:\5000\tom\jiafei中,那么就不需要修改classpath。要特别注意的是,因为SquareEquation.java有包名,切不可将SquareEquation.java以及它的字节码文件存放在d:\5000中,即不可以和Sunrise.java的字节码存放在一起,请进行如下的练习:

1. 将SquareEquation.java存放在D:\5000\tom\jiafei中,编译:

D:\5000\tom\jiafei\javac SquareEquation.java

2. 将Sunrise.java存放到D:\5000中,编译:

D:\5000\javac Sunrise.java

3. 运行:

java Sunrise

《Java程序设计》

实验项目四  继承与接口

一、实验目的

1. 巩固如下概念:

子类的继承性;

子类对象的创建过程;

成员变量的继承与隐藏;

方法的继承与重写。

2. 掌握上转型对象的使用;

3. 掌握接口回调技术。

二、实验准备

实验1.继承

  • 实验要求:

编写一个Java应用程序,除了主类外,该程序还有4个类:People、ChinaPeople、AmericanPeople和BeijingPeople类。

People类的访问权限是protected的double型成员变量:height和weight,以及public void speakHello()、public void averageHeight()和public void averageWeight()方法。

ChinaPeople类是People的子类,新增了public void chinaGongfu()方法。要求ChinaPeople重写父类public void speakHello()、public void averageHeight()和public void averageWeight()方法。

AmericanPeople类是People的子类,新增public void americanBoxing()方法。要求AmericanPeople重写父类的public void speakHello()、public void averageHeight()和public void averageWeight()方法。

BeijingPeople类是ChinaPeople的子类,新增public void beijingOpera()方法。要求ChinaPeople重写父类的public void speakHello()、public void averageHeight()和public void averageWeight()方法。

  • 实验效果:

你好,吃饭了吗?

How do You do

您好

中国人的平均身高:173.0厘米

American Average height:188.0cm

北京人的平均身高:167.0厘米

中国人的平均体重:67.34公斤

American Average weight:80.23kg

北京人的平均体重:68.5公斤

坐如钟,站如松,睡如弓

直拳、钩拳

京剧术语

坐如钟,站如松,睡如弓

  • 程序模板

Example.java

class People

{

protected double weight,height;

public void speakHello()

{

System.out.println("yayawawa");

}

public void averageHeight()

{

height=173;

System.out.println("average height:"+height);

}

public void averageWeight()

{

weight=70;

System.out.println("average weight:"+weight);

}

}

class ChinaPeople extends People

{

【代码1】

//重写public void speakHello()方法,要求输出类似“你好,吃了吗”这样的

//汉语信息

【代码2】 //重写public void averageHeight()方法,要求输出类似

//“中国人的平均身高:168.78厘米”这样的汉语信息

【代码3】 //重写public void averageWeight()方法,

//要求输出类似“中国人的平均体重:65公斤”这样的汉语信息

public void chinaGongfu()

{

【代码4】//输出中国武术的信息,例如:"坐如钟,站如松,睡如弓"等

}

}

class AmericanPeople  extends People

{

【代码5】 //重写public void speakHello()方法,要求输出类似

//“How do you do”这样的英语信息。

【代码6】 //重写public void averageHeight()方法

【代码7】 //重写public void averageWeight()方法

public void americanBoxing()

{

【代码8】//输出拳击的信息,例如,“直拳”、“钩拳”等

}

}

class BeijingPeople extends ChinaPeople

{

【代码9】

//重写public void speakHello()方法,要求输出类似“您好”这样的汉语信息

【代码10】 //重写public void averageHeight()方法

【代码11】 //重写public void averageWeight()方法

public void beijingOpera()

{

【代码12】//输出京剧的信息

}

}

public class Example

{

public static void main(String args[])

{

ChinaPeople chinaPeople=new ChinaPeople();

AmericanPeople americanPeople=new AmericanPeople();

BeijingPeople beijingPeople=new BeijingPeople();

chinaPeople.speakHello();

americanPeople.speakHello();

beijingPeople.speakHello();

chinaPeople.averageHeight();

americanPeople.averageHeight();

beijingPeople.averageHeight();

chinaPeople.averageWeight();

americanPeople.averageWeight();

beijingPeople.averageWeight();

chinaPeople.chinaGongfu();

americanPeople.americanBoxing();

beijingPeople.beijingOpera() ;

beijingPeople.chinaGongfu();

}

}

  • 实验后的练习:

就本程序而言,People类中的

public void speakHello()

public void averageHeight()

public void averageWeight()

实验2上转型对象

  • 实验要求:

要求有一个abstract类,类名为Employee。Employee的子类有YearWorker、MonthWorker和WeekWorker。YearWorker对象按年领取薪水,MonthWorker按月领取薪水,WeekWorker按周领取薪水。Employee类有一个abstract方法:

Public abstract earings();

子类必须重写父类的earnings()方法,给出各自领取报酬的具体方式。

有一个Company类,该类用Employee数组作为成员,Employee数组的单元可以是YearWorker对象的上转型对象、MonthWorker对象的上转型对象或WeekWorker对象的上转型对象。程序能输出Company对象一年需要支付的薪水总额。

  • 实验效果:

公司年工资总额:675202.736

  • 程序模板:

HardWork.java

abstract class Employee

{

public abstract double earnings();

}

class YearWorker extends Employee

{

【代码1】 //重写earnings()方法

}

class MonthWorker extends Employee

{

【代码2】 //重写earnings()方法。

}

class WeekWorker extends Employee

{

【代码3】 //重写earnings()方法。

}

class Company

{

Employee[] employee;

double salaries=0;

Company(Employee[] employee)

{

this.employee=employee;

}

public double salariesPay()

{

salaries=0;

【代码4】 //计算salaries。

return salaries;

}

}

public class HardWork

{

public static void main(String args[])

{

Employee[] employee=new Employee[20];

for(int i=0;i<employee.length;i++)

{

if(i%3==0)

employee[i]=new WeekWorker();

else if(i%3==1)

employee[i]=new MonthWorker();

else if(i%3==2)

employee[i]=new YearWorker();

}

Company  company=new Company(employee);

System.out.println("公司年工资总额:"+company.salariesPay());

}

}

  • 实验后的练习:

子类YearWorker如果不重写earnings方法,程序编译时提示怎样的错误?

实验3接口回调

  • 实验要求:

卡车要装载一批货物,货物有3种商品:电视、计算机和洗衣机。需要计算出大货车和小火车各自所装载的3中货物的总重量。

要求有一个ComputeWeight接口,该接口中有一个方法:

public double computeWeight()

有3个实现该接口的类:Television、Computer和WashMachine。这3个类通过实现接口computeTotalSales给出自重。

有一个Car类,该类用ComputeWeight接口类型的数组作为成员,那么该数组的单元就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Car对象所装载的货物的总重量。

  • 实验效果:

大货车装载的货物重量:4207.0

小货车装载的货物重量:1837.5

  • 程序模板:

Road.java

interface ComputerWeight

{

public double computeWeight();

}

class Television implements ComputerWeight

{   【代码1】 //实现computeWeight()方法。

}

class Computer implements ComputerWeight

{   【代码2】 //实现computeWeight()方法。

}

class WashMachine implements ComputerWeight

{  【代码3】 //实现computeWeight()方法。

}

class Car

{  ComputerWeight[] goods;

double totalWeights=0;

Car(ComputerWeight[] goods)

{

this.goods=goods;

}

public double getTotalWeights()

{

totalWeights=0;

【代码4】 //计算totalWeights

return totalWeights;

}

}

public class Road

{

public static void main(String args[])

{  ComputerWeight[] goodsOne=new ComputerWeight[50],

goodsTwo=new ComputerWeight[22] ;

for(int i=0;i<goodsOne.length;i++)

{   if(i%3==0)

goodsOne[i]=new Television();

else if(i%3==1)

goodsOne[i]=new Computer();

else if(i%3==2)

goodsOne[i]=new WashMachine();

}

for(int i=0;i<goodsTwo.length;i++)

{   if(i%3==0)

goodsTwo[i]=new Television();

else if(i%3==1)

goodsTwo[i]=new Computer();

else if(i%3==2)

goodsTwo[i]=new WashMachine();

}

Car  大货车=new Car(goodsOne);

System.out.println("大货车装载的货物重量:"+大货车.getTotalWeights());

Car  小货车=new Car(goodsTwo);

System.out.println("小货车装载的货物重量:"+小货车.getTotalWeights());

}

}

  • 实验后的练习:

请在实验的基础上再写一个实现ComputerWeight接口的类,比如Refrigerrator。这样一来,大货车或小货车装载的货物中就可以有Refrigerrator类型的对象。

增加一个实现ComputerWeight接口的类后,Car类需要进行修改吗?

《Java程序设计》

实验项目五  字符串、时间与数字类

一、实验目的

1. 掌握String类的常用方法;

2. 掌握Date类以及Calendar类的常用方法;

3. 掌握BigInteger类的常用方法。

二、实验准备

实验1.String类的常用方法

  • 实验要求:

编写一个Java应用程序,判断两个字符串是否相同,判断字符串的前缀、后缀是否和某个字符串相同,按字典顺序比较两个字符串的大小关系,检索字符串,创建字符串,将数字型字符串转换为数字,将字符串存放到数组中,用字符数组创建字符串。。

  • 程序模板

StringExample.java

class StringExample

{   public static void main(String args[])

{   String s1=new String("you are a student"),

s2=new String("how are you");

if(【代码1】) // 使用equals方法判断s1与s2是否相同

{

System.out.println("s1与s2相同");

}

else

{

System.out.println("s1与s2不相同");

}

String s3=new String("22030219851022024");

if(【代码2】)   //判断s3的前缀是否是“220302”。

{

System.out.println("吉林省的身份证");

}

String s4=new String("你"),

s5=new String("我");

if(【代码3】)//按着字典序s4大于s5的表达式。

{

System.out.println("按字典序s4大于s5");

}

else

{

System.out.println("按字典序s4小于s5");

}

int position=0;

String path="c:\\java\\jsp\\A.java";

position=【代码5】 //获取path中最后出现目录分隔符号的位置

System.out.println("c:\\java\\jsp\\A.java中最后出现\\的位置:"+position);

String fileName=【代码6】//获取path中“A.java”子字符串。

System.out.println("c:\\java\\jsp\\A.java中含有的文件名:"+fileName);

String s6=new String("100"), s7=new String("123.678");

int n1=【代码7】     //将s6转化成int型数据。

double n2=【代码8】  //将s7转化成double型数据。

double m=n1+n2;

System.out.println(m);

String s8=【代码9】//String调用valuOf(int n)方法将m转化为字符串对象

position=s8.indexOf(".");

String temp=s8.substring(position+1);

System.out.println("数字"+m+"有"+temp.length()+"位小数") ;

String s9=new String("ABCDEF");

char a[]=【代码10】   //将s8存放到数组a中。

for(int i=a.length-1;i>=0;i--)

{

System.out.print(" "+a[i]);

}

}

}

  • 实验后的练习:

1. 程序中的s6改写成

String s6=new String(“1a12b”);

运行时提示怎样的错误?

2. 请用数组a的前3个单元创建一个字符串并输出该串。

3. 请给出获取path中“jsp”子字符串的代码。

4. 在程序的适当位置增加如下代码,注意输出的结果。

String str1=new String(“ABCABC”),

str2=null,

str3=null,

str4=null;

str2=str1.replaceAll(“A”,”First”);

str3=str2.replaceAll(“B”,”Second”);

str4=str3.replaceAll(“C”,”Third”);

System.out.println(str1);

System.out.println(str2);

System.out.println(str3);

System.out.println(str4);

5. 可以使用Long类中的下列static方法得到整数各种进制的字符串表示:

Public static String toBinaryString(long i)

Public static String toOctalString(long i)

Public static String toHexString(long i)

Public static String toString(long i,int p)

其中的toString(long i, int p)返回整数i的p进制表示。请在适当位置添加代码输出12345的二进制、八进制和十六进制表示。

6. 在适当位置添加代码,分别输出数字m的整数部分和小数部分。

实验2.比较日期的大小

  • 实验要求:

编写一个Java应用程序,用户从输入对话框输入了两个日期,程序将判断两个日期的大小关系,以及两个日期之间的间隔天数。

  • 程序模板:

DateExample

import java.util.*;

import javax.swing.JOptionPane;

public class DateExample

{

public static void main(String args[ ])

{

String str=JOptionPane.showInputDialog("输入第一个日期的年份:");

int yearOne=Integer.parseInt(str);

str=JOptionPane.showInputDialog("输入该年的月份:");

int monthOne=Integer.parseInt(str);

str=JOptionPane.showInputDialog("输入该月份的日期:");

int dayOne=Integer.parseInt(str);

str=JOptionPane.showInputDialog("输入第二个日期的年份:");

int yearTwo=Integer.parseInt(str);

str=JOptionPane.showInputDialog("输入该年的月份:");

int monthTwo=Integer.parseInt(str);

str=JOptionPane.showInputDialog("输入该月份的日期:");

int dayTwo=Integer.parseInt(str);

Calendar calendar=【代码1】  //初始化日历对象

【代码2】//将calendar的时间设置为yearOne年monthOne月dayOne日

long timeOne=【代码3】     //calendar表示的时间转换成毫秒

【代码4】//将calendar的时间设置为yearTwo年monthTwo月dayTwo日

long timeTwo=【代码5】    //calendar表示的时间转换成毫秒。

Date date1=【代码6】       // 用timeOne做参数构造date1

Date date2=【代码7】      // 用timeTwo做参数构造date2

if(date2.equals(date1))

{

System.out.println("两个日期的年、月、日完全相同");

}

else if(date2.after(date1))

{

System.out.println("您输入的第二个日期大于第一个日期");

}

else if(date2.before(date1))

{

System.out.println("您输入的第二个日期小于第一个日期");

}

long days=【代码8】//计算两个日期相隔天数

System.out.println(yearOne+"年"+monthOne+"月"+dayOne+"日和"

+yearTwo+"年"+monthTwo+"月"+dayTwo+"相隔"+days+"天");

}

}

  • 实验后的练习:

1. Calendar对象可以将时间设置到年、月、日、时、分、秒。请改进上面的程序,使用户输入的两个日期包括时、分、秒。

2. 根据本程序中的一些知识,编写一个计算利息(按天计算)的程序。从输入对话框输入存款的数目和起止时间。

实验3.处理大整数

  • 实验要求:

编写一个Java应用程序,计算两个大整数的和、差、积和商,并计算一个大整数的因子个数(因子中不包括1和大整数本身)。

  • 程序模板

BigintegerExample

import java.math.*;

class BigIntegerExample

{

public static void main(String args[])

{   BigInteger n1=new BigInteger("987654321987654321987654321"),

n2=new BigInteger("123456789123456789123456789"),

result=null;

result=【代码1】//n1和n2做加法运算

System.out.println("和:"+result.toString());

result=【代码2】//n1和n2做减法运算

System.out.println("差:"+result.toString());

result=【代码3】//n1和n2做乘法运算

System.out.println("积:"+result.toString());

result=【代码4】//n1和n2做除法运算

System.out.println("商:"+result.toString());

BigInteger m=new BigInteger("1968957"),

COUNT=new BigInteger("0"),

ONE=new BigInteger("1"),

TWO=new BigInteger("2");

System.out.println(m.toString()+"的因子有:");

for(BigInteger i=TWO;i.compareTo(m)<0;i=i.add(ONE))

{  if((n1.remainder(i).compareTo(BigInteger.ZERO))==0)

{  COUNT=COUNT.add(ONE);

System.out.print("  "+i.toString());

}

}

System.out.println("");

System.out.println(m.toString()+"一共有"+COUNT.toString()+"个因子");

}

}

  • 实验后的练习:

1. 编写程序,计算大整数的阶乘。

2. 编写程序,计算1+2+3…的前999999999项的和。

《Java程序设计》

实验项目六  组件与事件处理(1)

一、实验目的

1.学习处理ActionEvent事件;

2.学习处理ItemEvent事件和paint方法;

3.学习使用布局类。

二、实验内容

实验1.算术测试

  • 实验要求:

编写一个算书测试小软件,用来训练小学生的算术能力。程序由3个类组成,其中Teacher类对象负责给出算术题目,并判断回答者的答案是否正确;ComputerFrame类对象负责为算术题目提供视图,比如用户可以通过ComputerFrame类对象提供的GUI界面看到题目,并通过该GUI界面给出题目的答案;MainClass是软件的主类。

  • 程序模板:

Teacher.java

public class Teacher

{  int numberOne,numberTwo;

String operator="";

boolean right;

public int giveNumberOne(int n)

{  numberOne=(int)(Math.random()*n)+1;

return numberOne;

}

public int giveNumberTwo(int n)

{  numberTwo=(int)(Math.random()*n)+1;

return numberTwo;

}

public String giveOperator()

{  double d=Math.random();

if(d>=0.5)

operator="+";

else

operator="-";

return operator;

}

public boolean getRight(int answer)

{  if(operator.equals("+"))

{  if(answer==numberOne+numberTwo)

right=true;

else

right=false;

}

else if(operator.equals("-"))

{  if(answer==numberOne-numberTwo)

right=true;

else

right=false;

}

return right;

}

}

ComputerFrame.java

import java.awt.*;

import java.awt.event.*;

public class ComputerFrame extends Frame implements ActionListener

{  TextField textOne,textTwo,textResult;

Button getProblem,giveAnwser;

Label operatorLabel,message;

Teacher teacher;

ComputerFrame(String s)

{ super(s);

teacher=new Teacher();

setLayout(new FlowLayout());

textOne=【代码1】     //创建textOne,其可见字符长是10

textTwo=【代码2】     //创建textTwo,其可见字符长是10

textResult=【代码3】  //创建textResult,其可见字符长是10

operatorLabel=new Label("+");

message=new Label("你还没有回答呢");

getProblem=new Button("获取题目");

giveAnwser=new Button("确认答案");

add(getProblem);

add(textOne);

add(operatorLabel);

add(textTwo);

add(new Label("="));

add(textResult);

add(giveAnwser);

add(message);

textResult.requestFocus();

textOne.setEditable(false);

textTwo.setEditable(false);

【代码4】//将当前窗口注册为getProblem的ActionEvent事件监视器

【代码5】//将当前窗口注册为giveAnwser的ActionEvent事件监视器

【代码6】//将当前窗口注册为textResult的ActionEvent事件监视器

setBounds(100,100,450,100);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{public void windowClosing(WindowEvent e)

{  System.exit(0);

}

}

);

}

public void actionPerformed(ActionEvent e)

{ if(【代码7】) //判断事件源是否是getProblem

{ int number1=teacher.giveNumberOne(100);

int number2=teacher.giveNumberTwo(100);

String operator=teacher.givetOperator();

textOne.setText(""+number1);

textTwo.setText(""+number2);

operatorLabel.setText(operator);

message.setText("请回答");

textResult.setText(null);

}

if(【代码8】) //判断事件源是否是giveAnwser

{  String answer=textResult.getText();

try{

int result=Integer.parseInt(answer);

if(teacher.getRight(result)==true)

{  message.setText("你回答正确");

}

else

{ message.setText("你回答错误");

}

}

catch(NumberFormatException ex)

{  message.setText("请输入数字字符");

}

}

textResult.requestFocus();

validate();

}

}

MainClass.java

public class MainClass

{ public static void main(String args[])

{  ComputerFrame frame;

frame=【代码9】//创建窗口,其标题为:算术测试

}

}

  • 实验后的练习:

1. 给上述程序增加测试乘、除的功能。

实验2.信号灯

  • 实验要求:

编写一个带有窗口的应用程序。在窗口的北面添加一个下拉列表,该下拉列表有“”、“”和“”三个选项。在窗口的中心添加一个画布,当用户在下拉列表选择某项后,画布上绘制相应的信号灯。

  • 程序模板:

SignalCanvas.java

import java.awt.*;

public class SignalCanvas extends Canvas

{  int red,green,yellow,x,y,r;

SignalCanvas()

{  setBackground(Color.white);

}

public void setRed(int r)

{   red=r;

}

public void setGreen(int g)

{   green=g;

}

public void setYellow(int y)

{   yellow=y;

}

public void setPosition(int x,int y)

{  this.x=x;

this.y=y;

}

public void setRadius(int r)

{  this.r=r;

}

public void paint(Graphics g)

{  if(red==1)

{  g.setColor(Color.red);

}

else if(green==1)

{  g.setColor(Color.green);

}

else if(yellow==1)

{  g.setColor(Color.yellow);

}

g.fillOval(x,y,2*r,2*r);

}

}

SignalFrame.java

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class SignalFrame extends Frame implements ItemListener

{  Choice choice;

SignalCanvas signal=null;

String itemRed="红灯",itemYellow="黄灯",itemGreen="绿灯";

public SignalFrame()

{  choice=【代码1】          //创建choice

【代码2】                //创建choice添加itemRed

【代码3】                //创建choice添加itemYellow

【代码4】                //创建choice添加itemGreen

【代码5】  //将当前窗口注册为choice的ItemEvent事件监视器

add(choice,BorderLayout.NORTH);

try{  Class cs=Class.forName("SignalCanvas");

signal=(SignalCanvas)cs.newInstance();

add(signal,BorderLayout.CENTER);

}

catch(Exception e)

{ add(new Label("您还没有编写SignalCanvas类"),BorderLayout.CENTER);

}

setBounds(100,100,360,300);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{  public void windowClosing(WindowEvent e)

{  System.exit(0);

}

}

);

}

public void itemStateChanged(ItemEvent e)

{  String item= 【代码6】  // choice返回被选中的条目

int w=signal.getBounds().width;

int h=signal.getBounds().height;

int m=Math.min(w,h);

signal.setRadius(m/6);

if(item.equals(itemRed))

{ if(signal!=null)

{ signal.setRed(1);

signal.setYellow(0);

signal.setGreen(0);

signal.setPosition(w/3,0);

signal.repaint();

}

}

else if(item.equals(itemYellow))

{ if(signal!=null)

{ signal.setRed(0);

signal.setYellow(1);

signal.setGreen(0);

signal.setPosition(w/3,h/3);

signal.repaint();

}

}

else if(item.equals(itemGreen))

{ if(signal!=null)

{ signal.setRed(0);

signal.setYellow(0);

signal.setGreen(1);

signal.setPosition(w/3,2*h/3);

signal.repaint();

}

}

}

}

SignalMainClass.java

public class SignalMainClass

{ public static void main(String args[])

{  SignalFrame frame;

frame=new SignalFrame() ;

frame.setTitle("信号灯");

}

}

  • 实验后的练习:

1. 改进上述程序,在下拉列表中增加“熄灭所有灯”选项,当选中该项时,画布上绘制一个半径为0,位置是(0,0)的圆。

实验3.布局与日历

  • 实验要求:

编写一个应用程序,有一个窗口,该窗口为BorderLayout布局。窗口的中心添加一个Panel容器:pCenter,pCenter的布局是7行7列的GriderLayout布局,pCenter中放置49个标签,用来显示日历。窗口的北面添加一个Panel容器pNorth,其布局是FlowLayout布局,pNorth放置两个按钮:nextMonth和previousMonth,单击nextMonth按钮,可以显示当前月的下一月的日历;单击previousMonth按钮,可以显示当前月的上一月的日历。窗口的南面添加一个Panel容器pSouth,其布局是FlowLayout布局,pSouth中放置一个标签用来显示一些信息。

  • 程序模板:

CalendarBean.java

import java.util.Calendar;

public class CalendarBean

{

String  day[];

int year=2005,month=0;

public void setYear(int year)

{    this.year=year;

}

public int getYear()

{    return year;

}

public void setMonth(int month)

{    this.month=month;

}

public int getMonth()

{    return month;

}

public String[] getCalendar()

{   String a[]=new String[42];

Calendar 日历=Calendar.getInstance();

日历.set(year,month-1,1);

int 星期几=日历.get(Calendar.DAY_OF_WEEK)-1;

int day=0;

if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)

{  day=31;

}

if(month==4||month==6||month==9||month==11)

{  day=30;

}

if(month==2)

{  if(((year%4==0)&&(year%100!=0))||(year%400==0))

{   day=29;

}

else

{   day=28;

}

}

for(int i=星期几,n=1;i<星期几+day;i++)

{

a[i]=String.valueOf(n) ;

n++;

}

return a;

}

}

CalendarFrame.java

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class CalendarFrame extends Frame implements ActionListener

{    Label labelDay[]=new Label[42];

Button titleName[]=new Button[7];

String name[]={"日","一","二","三", "四","五","六"};

Button nextMonth,previousMonth;

int year=2006,month=10;

CalendarBean calendar;

Label showMessage=new Label("",Label.CENTER);

public CalendarFrame()

{  Panel pCenter=new Panel();

【代码1】 //将pCenter的布局设置为7行7列的GridLayout 布局。

for(int i=0;i<7;i++)

{  titleName[i]=new Button(name[i]);

【代码2】//pCenter添加组件titleName[i]。

}

for(int i=0;i<42;i++)

{

labelDay[i]=new Label("",Label.CENTER);

【代码3】//pCenter添加组件labelDay[i]。

}

calendar=new  CalendarBean();

calendar.setYear(year);

calendar.setMonth(month);

String day[]=calendar.getCalendar();

for(int i=0;i<42;i++)

{  labelDay[i].setText(day[i]);

}

nextMonth=new Button("下月");

previousMonth=new Button("上月");

nextMonth.addActionListener(this);

previousMonth.addActionListener(this);

Panel pNorth=new Panel(),

pSouth=new Panel();

pNorth.add(previousMonth);

pNorth.add(nextMonth);

pSouth.add(showMessage);

showMessage.setText("日历:"+calendar.getYear()+"年"+ calendar.getMonth()+"月" );

ScrollPane scrollPane=new ScrollPane();

scrollPane.add(pCenter);

【代码4】// 窗口添加scrollPane在中心区域

【代码5】//  窗口添加pNorth 在北面区域

【代码6】// 窗口添加pSouth 在南区域。

}

public void actionPerformed(ActionEvent e)

{  if(e.getSource()==nextMonth)

{ month=month+1;

if(month>12)

month=1;

calendar.setMonth(month);

String day[]=calendar.getCalendar();

for(int i=0;i<42;i++)

{ labelDay[i].setText(day[i]);

}

}

else if(e.getSource()==previousMonth)

{ month=month-1;

if(month<1)

month=12;

calendar.setMonth(month);

String day[]=calendar.getCalendar();

for(int i=0;i<42;i++)

{  labelDay[i].setText(day[i]);

}

}

showMessage.setText("日历:"+calendar.getYear()+"年"+calendar.getMonth()+"月" );

}

}

CalendarMainClass.java

public class CalendarMainClass

{ public static void main(String args[])

{   CalendarFrame frame=new CalendarFrame();

frame.setBounds(100,100,360,300);

frame.setVisible(true);

frame.validate();

frame.addWindowListener(new java.awt.event.WindowAdapter()

{  public void windowClosing(java.awt.event.WindowEvent e)

{  System.exit(0);

}

}

}

}

  • 实验后的练习:

    1. 请在CalendarFrame类中增加一个TextField文本框,用户可以通过在文本框中输入年份来修改calendar对象的int成员year。

《Java程序设计》

实验项目七  组件与事件处理(2)

一、实验目的

1.通过使用恰当的组件,给出计算一元二次方程根的GUI程序;

2.学习使用对话框;

3.学习焦点事件、鼠标和键盘事件。

二、实验内容

实验1.方程求根

  • 实验要求:

首先编写一个封装一元二次方程的类,然后再编写一个窗口。要求窗口使用三个文本框和一个文本区,为方程对象中的数据提供视图,其中三个文本框用来显示和更新方程对象的系数;文本区对象用来显示方程的根。窗口中有一个按钮,用户单击该按钮后,程序用文本框中的数据修改方程的系数,并将方程的根显示在文本区中。

  • 实验效果:

转存失败重新上传取消转存失败重新上传取消

图7-1 方程求根

  • 程序模板:

SquareEquation.java

public class SquareEquation

{   double a,b,c;

double root1,root2;

public void setA(double a)

{ this.a=a;

}

public void setB(double b)

{ this.b=b;

}

public void setC(double c)

{ this.c=c;

}

public double  getRootOne() throws NoRealRootException,NoSquareEquationException

{   if(a!=0)

{  double disk=b*b-4*a*c;

if(disk>=0)

{ root1=(-b+Math.sqrt(disk))/(2*a);

}

else

{  throw new NoRealRootException("没有实根");

}

}

else

{

throw new NoRealRootException("不是二次方程");

}

return root1;

}

public double  getRootTwo() throws NoRealRootException,NoSquareEquationException

{   if(a!=0)

{  double disk=b*b-4*a*c;

if(disk>=0)

{ root2=(-b-Math.sqrt(disk))/(2*a);

}

else

{  throw new NoRealRootException("没有实根");

}

}

else

{

throw new NoRealRootException("不是二次方程");

}

return root2;

}

}

class NoRealRootException extends Exception

{  String message;

NoRealRootException(String s)

{   message=s;

}

public String getMessage()

{   return message;

}

}

class NoSquareEquationException extends Exception

{  String message;

NoSquareEquationException(String s)

{   message=s;

}

public String getMessage()

{   return message;

}

}

EquationFrame.java

import java.awt.*;

import java.awt.event.*;

public class EquationFrame extends Frame implements ActionListener

{  SquareEquation equation;

TextField textA,textB,textC;

TextArea showRoots;

Button controlButton;

public EquationFrame()

{  equation=new SquareEquation();

textA=new TextField(8);

textB=new TextField(8);

textC=new TextField(8);

showRoots=new TextArea();

controlButton=new Button("确定");

Panel pNorth=new Panel();

pNorth.add(new Label("二次项系数:"));

pNorth.add(textA);

pNorth.add(new Label("一次项系数:"));

pNorth.add(textB);

pNorth.add(new Label("常数项系数:"));

pNorth.add(textC);

pNorth.add(controlButton);

【代码1】  //当前窗口作为controlButton的ActionEvent事件的监视器

add(pNorth,BorderLayout.NORTH);

add(showRoots,BorderLayout.CENTER);

setBounds(100,100,630,160);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{  public void windowClosing(WindowEvent e)

{  System.exit(0);

}

}

);

}

public void actionPerformed(ActionEvent e)

{  try{

double a=Double.parseDouble(【代码2】);

//textA调用方法获取其中的文本

double b=Double.parseDouble(【代码3】);

//textB调用方法获取其中的文本

double c=Double.parseDouble(【代码4】);

// textC调用方法获取其中的文本

equation.setA(a);

equation.setB(b);

equation.setC(c);

textA.setText(""+a);

textB.setText(""+b);

textC.setText(""+c);

showRoots.append("\n 根:"+equation.getRootOne());

showRoots.append("   根:"+equation.getRootTwo());

}

catch(Exception ex)

{  showRoots.append("\n"+ex+"\n");

}

}

}

EquationMainClass.java

public class EquationMainClass

{ public static void main(String args[])

{   EquationFrame frame=new EquationFrame();

}

}

  • 实验后的练习:

当计算出两个实根后,文本区中并没有显示是哪个方程的实根,请添加适当的代码,使得showRoots能显示目前正在求根的方程的各个系数。

实验2.字体对话框

  • 实验要求:

编写一个FontFamily类,该类对象可以获取当前机器可用的全部字体名称。

编写一个Dialog的子类:FontDialog,该类为FontFamily对象维护的数据提供视图,要求FontDialog对象使用下拉列表显示FontFamily对象维护的全部字体的名称,当选择了下拉列表中的某个字体名称后,FontDialog对象使用标签显示该字体的效果。要求对话框提供返回下拉列表中所选择的字体名称的方法。

编写一个窗口,该窗口有“设置字体”按钮和一个文本区对象,当单击该按钮时,弹出一个FontDialog创建的对话框,然后根据用户在对话框下拉列表中选择的字体来显示文本区中的文本。

  • 实验效果:

转存失败重新上传取消转存失败重新上传取消  转存失败重新上传取消转存失败重新上传取消

图7-2 字体对话框

  • 程序模板:

FontFamilyNames.java

import java.awt.GraphicsEnvironment;

public class FontFamilyNames

{  String fontName[];

public String [] getFontName()

{  GraphicsEnvironment ge=

GraphicsEnvironment.getLocalGraphicsEnvironment();

fontName=ge.getAvailableFontFamilyNames();

return fontName;

}

}

 FontDialog.java

import java.awt.event.*;

import java.awt.*;

import javax.swing.JLabel;

public class FontDialog extends Dialog implements ItemListener,ActionListener

{   FontFamilyNames fontFamilyNames;

int fontSize=38;

String fontName;

Choice fontNameList;

JLabel label;

Font font;

Button yes,cancel;

static int YES=1,NO=0;

int state=-1;

FontDialog(Frame f)

{ super(f);

fontFamilyNames=new FontFamilyNames();

【代码1】                            //对话框设置为有模式

yes=new Button("Yes");

cancel=new Button("cancel");

yes.addActionListener(this);

cancel.addActionListener(this);

label=new JLabel("hello,奥运",JLabel.CENTER);

fontNameList=new Choice();

String name[]=fontFamilyNames.getFontName();

for(int k=0;k<name.length;k++)

{  fontNameList.add(name[k]);

}

fontNameList.addItemListener(this);

add(fontNameList,BorderLayout.NORTH);

add(label,BorderLayout.CENTER);

Panel pSouth=new Panel();

pSouth.add(yes);

pSouth.add(cancel);

add(pSouth,BorderLayout.SOUTH);

setBounds(100,100,280,170);

addWindowListener(new WindowAdapter()

{    public void windowClosing(WindowEvent e)

{ state=NO;

setVisible(false);

}

}

);

validate();

}

public void itemStateChanged(ItemEvent e)

{ fontName=(String)fontNameList.getSelectedItem();

font=new Font(fontName,Font.BOLD,fontSize);

label.setFont(font);

label.repaint();

validate();

}

public void actionPerformed(ActionEvent e)

{ if(e.getSource()==yes)

{   state=YES;

【代码2】            //对话框设置为不可见

}

else if(e.getSource()==cancel)

{  state=NO;

【代码3】          //对话框设置为不可见

}

}

public int getState()

{  return state;

}

public Font getFont()

{  return font;

}

}

 FrameHaveDialog.java

import java.awt.event.*;

import java.awt.*;

import javax.swing.JTextArea;

public class FrameHaveDialog extends Frame implements ActionListener

{   JTextArea text;

Button buttonFont;

FrameHaveDialog()

{ buttonFont=new Button("设置字体");

text=new JTextArea("Java 2实用教程(第三版)");

buttonFont.addActionListener(this);

add(buttonFont,BorderLayout.NORTH);

add(text);

setBounds(60,60,300,300);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{  public void windowClosing(WindowEvent e)

{ System.exit(0);

}

}

);

}

public void actionPerformed(ActionEvent e)

{  if(e.getSource()==buttonFont)

{  FontDialog dialog=【代码4】       //创建对话框

【代码5】                         //对话框设置为可见

【代码6】                     //对话框设置设置标题为“字体对话框”

if(dialog.getState()==FontDialog.YES)

{ text.setFont(dialog.getFont());

text.repaint();

}

if(dialog.getState()==FontDialog.NO)

{ text.repaint();

}

}

}

}

FontDialogMainClass.java

public class FontDialogMainClass

{   public static void main(String args[])

{  new FrameHaveDialog();

}

}

  • 实验后的练习:

给上述实验中的对话框增加设置字体字号(字体大小)的功能。上述实验中,FontDialog类的fontSize成员的值是38,请在FontDialog类中再增加一个下拉列表,通过选择该列表的选项可以设置fontSize的值,以便灵活设置字体(font)的大小。比如,该列表有选项分别为“初号”、“一号”……“五号”等选项(五号相当于12磅),当用户选择“五号”选项时,fontSize的大小设置为12。

实验3.英语单词拼写训练

  • 实验要求:

编写一个应用程序,要求如下:

窗口中有一个TextField对象和一个按钮对象,将这两个对象添加到一个面板中,然后将该面板添加到窗口的北面。

用户在TextField对象中输入一个英文单词,然后回车或单击按钮,程序将创建若干个标签,其个数刚好等于英文单词所包含的字母的标签,而且每个标签上的名字刚好是英文单词中的一个字母。要求将这些标签按一行添加到一个面板中,然后将该面板添加到窗口的中心。

用户用鼠标单击一个标签后,通过按下键盘上的“->”、“<-”键交换相邻标签上的字母,使得这些标签上字母的排列顺序和英文单词中字母的顺序相同。

  • 实验效果

转存失败重新上传取消转存失败重新上传取消

图7-3 英语单词拼写训练

  • 程序模板:

RondomString.java

public class RondomString

{  String str="";

public String getRondomString(String s)

{ StringBuffer strBuffer=new StringBuffer(s);

int m=strBuffer.length();

for(int k=0;k<m;k++)

{  int index=(int)(Math.random()*strBuffer.length());

char c=strBuffer.charAt(index);

str=str+c;

strBuffer=strBuffer.deleteCharAt(index);

}

return str;

}

}

LetterLabel.java

import java.awt.*;

import java.awt.event.*;

public class LetterLabel extends Button implements FocusListener,MouseListener

{  LetterLabel()

{   【代码1】 //将当前对象注册为自身的焦点视器

【代码2】 //将当前对象注册为自身的标监视器

setBackground(Color.cyan);

setFont(new Font("",Font.BOLD,30));

}

public static  LetterLabel[] getLetterLabel(int n)

{  LetterLabel a[]=new LetterLabel[n];

for(int k=0;k<a.length;k++)

{  a[k]=new LetterLabel();

}

return a;

}

public void focusGained(FocusEvent e)

{  setBackground(Color.red);

}

public void focusLost(FocusEvent e)

{  setBackground(Color.cyan);

}

public void mousePressed(MouseEvent e)

{  requestFocus();

}

public void setText(char c)

{ setLabel(""+c);

}

public void mouseReleased(MouseEvent e){}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mouseClicked(MouseEvent e){}

}

SpellingWordFrame.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.Box;

public class SpellingWordFrame extends Frame implements KeyListener,ActionListener

{ TextField inputWord;

Button button;

LetterLabel label[];

Panel northP,centerP;

Box wordBox;

String hintMessage="用鼠标单击字母,按左右箭头交换字母,将其排列成所输入的单词";

Label messaageLabel=new Label(hintMessage);

String word="";

SpellingWordFrame()

{ inputWord=new TextField(12);

button=new Button("确定");

button.addActionListener(this);

inputWord.addActionListener(this);

northP=new Panel();

northP.add(new Label("输入一个英文单词:"));

northP.add(inputWord);

northP.add(button);

centerP=new Panel();

wordBox=Box.createHorizontalBox();

centerP.add(wordBox);

add(northP,BorderLayout.NORTH);

add(centerP,BorderLayout.CENTER);

add(messaageLabel,BorderLayout.SOUTH);

setBounds(100,100,350,180);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{ public void windowClosing(WindowEvent e)

{ System.exit(0);

}

}

);

}

public void actionPerformed(ActionEvent e)

{  word=inputWord.getText();

int n=word.length();

RondomString rondom=new RondomString();

String randomWord=rondom.getRondomString(word);

wordBox.removeAll();

messaageLabel.setText(hintMessage);

if(n>0)

{  label=LetterLabel.getLetterLabel(n);

for(int k=0;k<label.length;k++)

{  【代码3】 //将当前窗口注册为label[k]的键盘监视器

label[k].setText(randomWord.charAt(k));

wordBox.add(label[k]);

}

validate();

inputWord.setText(null);

label[0].requestFocus();

}

}

public void keyPressed(KeyEvent e)

{  LetterLabel sourceLabel=(LetterLabel)e.getSource();

int index=-1;

if(【代码4】) //判断按下的是否是←键)

{  for(int k=0;k<label.length;k++)

{  if(label[k]==sourceLabel)

{  index=k;

break;

}

}

if(index!=0)

{ String temp=label[index].getLabel();

label[index].setText(label[index-1].getLabel());

label[index-1].setText(temp);

label[index-1].requestFocus();

}

}

else if(【代码5】) //判断按下的是否是→键

{  for(int k=0;k<label.length;k++)

{  if(label[k]==sourceLabel)

{  index=k;

break;

}

}

if(index!=label.length-1)

{ String temp=label[index].getLabel();

label[index].setText(label[index+1].getLabel());

label[index+1].setLabel(temp);

label[index+1].requestFocus();

}

}

validate();

}

public void keyTyped(KeyEvent e){}

public void keyReleased(KeyEvent e)

{  String success="";

for(int k=0;k<label.length;k++)

{  String str=label[k].toString();

success=success+str;

}

if(success.equals(word))

{  messaageLabel.setText("恭喜你,你成功了");

for(int k=0;k<label.length;k++)

{ label[k].removeKeyListener(this);

label[k].removeFocusListener(label[k]);

label[k].setBackground(Color.green);

}

inputWord.requestFocus();

}

}

}

WordMainClass.java

public class WordMainClass

{   public static void main(String args[])

{  new SpellingWordFrame();

}

}

  • 实验后的练习:

增加记录用户移动字母次数的功能,即当用户拼写成功后,messageLabel标签显示的信息中包含用户移动字母的次数。
《Java程序设计》

实验项目八  多线程

一、实验目的

1. 掌握使用Thread的子类创建线程;

2. 学习使用Thread类创建线程;

3. 学习处理线程同步问题。

二、实验内容

实验1.汉字打字练习

  • 实验要求:

编写一个Java应用程序,在主线程中再创建一个Frame类型的窗口,在该窗口中再创建1个线程giveWord。线程giveWord每隔2秒钟给出一个汉字,用户使用一种汉字输入法将该汉字输入到文本框中。

  • 实验效果:

转存失败重新上传取消转存失败重新上传取消

图8-1 汉字打字练习

  • 程序模板:

WordThread.java

import java.awt.*;

public class WordThread extends Thread

{   char word;

int k=19968;

Label com;

WordThread(Label com)

{  this.com=com;

}

public void run()

{  k=19968;

while(true)

{

word=(char)k;

com.setText(""+word);

try{  【代码1】//调用sleep方法使得线程中断6000豪秒

}

catch(InterruptedException e){}

k++;

if(k>=29968) k=19968;

}

}

}

ThreadFrame.java

import java.awt.*;

import java.awt.event.*;

public class ThreadFrame extends Frame implements ActionListener

{

Label  wordLabel;

Button button;

TextField inputText,scoreText;

【代码2】//用WordThread声明一个giveWord对象

int score=0;

ThreadFrame()

{ wordLabel=new Label(" ",Label.CENTER);

wordLabel.setFont(new Font("",Font.BOLD,72));

button=new Button("开始");

inputText=new TextField(3);

scoreText=new TextField(5);

scoreText.setEditable(false);

【代码3】//创建giveWord,将wordLabel传递给WordThread构造方法的参数

button.addActionListener(this);

inputText.addActionListener(this);

add(button,BorderLayout.NORTH);

add(wordLabel,BorderLayout.CENTER);

Panel southP=new Panel();

southP.add(new Label("输入标签所显示的汉字后回车:"));

southP.add(inputText);

southP.add(scoreText);

add(southP,BorderLayout.SOUTH);

setBounds(100,100,350,180);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{ public void windowClosing(WindowEvent e)

{ System.exit(0);

}

}

);

}

public void actionPerformed(ActionEvent e)

{

if(e.getSource()==button)

{  if(!(【代码4】))     //giveWord调用方法isAlive()

{    giveWord=new WordThread(wordLabel);

}

try

{    【代码5】//giveWord调用方法start()

}

catch(Exception exe){}

}

else if(e.getSource()==inputText)

{  if(inputText.getText().equals(wordLabel.getText()))

{  score++;

}

scoreText.setText("得分:"+score);

inputText.setText(null);

}

}

}

ThreadWordMainClass.java

public class ThreadWordMainClass

{  public static void main(String args[])

{  new ThreadFrame();

}

  • 实验后的练习:

1. 在WordThread类中增加int型的成员time,其初值为6000,将其中的【代码1】更改为线程中断time毫秒。在WordThread类增加public void setTime(int n)方法,使得WordThread线程对象可以调用该方法修改time的值。

实验2.旋转的行星

  • 实验要求:

编写一个应用程序,模拟月亮围绕地球旋转、地球围绕太阳旋转。

  • 实验效果:

转存失败重新上传取消转存失败重新上传取消

图8-2 旋转的行星

  • 程序模板:

Mycanvas.java

import java.awt.*;

public class Mycanvas extends Canvas

{  int r;

Color c;

public void setColor(Color c)

{ this.c=c;

}

public void setR(int r)

{  this.r=r;

}

public void paint(Graphics g)

{ g.setColor(c);

g.fillOval(0,0,2*r,2*r);

}

public int getR()

{  return r;

}

}

Planet.java

import java.awt.*;

public class Planet extends Panel implements Runnable

{  【代码1】     //用Thread类声明一个moon对象

Mycanvas yellowBall;

double pointX[]=new double[360],

pointY[]=new double[360]; //用来表示画布左上角端点坐标的数组

int w=100,h=100;

int radius=30;

Planet()

{ setSize(w,h);

setLayout(null);

yellowBall=new Mycanvas();

yellowBall.setColor(Color.yellow);

add(yellowBall);

yellowBall.setSize(12,12);

yellowBall.setR(12/2);

pointX[0]=0;

pointY[0]=-radius;

double angle=1*Math.PI/180;   //刻度为1度

for(int i=0;i<359;i++)        //计算出数组中各个元素的值

{ pointX[i+1]=pointX[i]*Math.cos(angle)-Math.sin(angle)*pointY[i];

pointY[i+1]=pointY[i]*Math.cos(angle)+pointX[i]*Math.sin(angle);

}

for(int i=0;i<360;i++)

{ pointX[i]=pointX[i]+w/2;    //坐标平移

pointY[i]=pointY[i]+h/2;

}

yellowBall.setLocation((int)pointX[0]-yellowBall.getR(),

(int)pointY[0]-yellowBall.getR());

【代码2】 //创建 moon线程,当前面板做为该线程的目标对象

}

public void start()

{  try{  moon .start();

}

catch(Exception exe){}

}

public void paint(Graphics g)

{ g.setColor(Color.blue);

g.fillOval(w/2-9,h/2-9,18,18);

}

public void run()

{ int i=0;

while(true)

{  i=(i+1)%360;

yellowBall.setLocation((int)pointX[i]-yellowBall.getR(),

(int)pointY[i]-yellowBall.getR());

try{ 【代码3】 // Thread类调用类方法sleep使得线程中断10豪秒

}

catch(InterruptedException e){}

}

}

}

HaveThreadFrame.java

import java.awt.*;

import java.awt.event.*;

public class HaveThreadFrame extends Frame implements Runnable

{ 【代码4】     //用Thread类声明一个rotate对象

Planet earth;

double pointX[]=new double[360],

pointY[]=new double[360];

int width,height;

int radius=120;

HaveThreadFrame()

{  rotate=new Thread(this);

earth=new Planet();

setBounds(0,0,360,400);

width=getBounds().width;

height=getBounds().height;

pointX[0]=0;

pointY[0]=-radius;

double angle=1*Math.PI/180;

for(int i=0;i<359;i++)

{ pointX[i+1]=pointX[i]*Math.cos(angle)-Math.sin(angle)*pointY[i];

pointY[i+1]=pointY[i]*Math.cos(angle)+pointX[i]*Math.sin(angle);

}

for(int i=0;i<360;i++)

{ pointX[i]=pointX[i]+width/2;

pointY[i]=pointY[i]+height/2;

}

setLayout(null);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{ public void windowClosing(WindowEvent e)

{ System.exit(0);

}

}

);

add(earth);

earth.setLocation((int)pointX[0]-earth.getSize().width/2,

(int)pointY[0]-earth.getSize().height/2);

earth.start();

【代码5】     //用rotate调用start方法

}

public void run()

{ int i=0;

while(true)

{  i=(i+1)%360;

earth.setLocation((int)pointX[i]-earth.getSize().width/2,

(int)pointY[i]-earth.getSize().height/2);

try{ Thread.sleep(100);

}

catch(InterruptedException e){}

}

}

public void paint(Graphics g)

{ g.setColor(Color.red);

g.fillOval(width/2-15,height/2-15,30,30);

}

}

ThreadRotateMainClass.java

public class ThreadRotateMainClass

{  public static void main(String args[])

{  new HaveThreadFrame();

}

}

  • 实验后的练习:

1. 在Planet类中再增加一个Mycanvas对象greenBall和一个Thread对象Satellite,线程Satellite占有CPU资源期间可以让greenBall画布旋转。

实验3.双线程接力

  • 实验要求:

编写一个应用程序,除了主线程外,还有两个线程:first和second。first负责模拟一个红色的按钮从坐标(10,60)运动到(100,60);second负责模拟一个绿色的按钮从坐标(100,60)运动到(200,60)。

  • 实验效果:

转存失败重新上传取消转存失败重新上传取消

图8-3 双线程接力

  • 程序模板

MoveButton.java

import java.awt.*;

import java.awt.event.*;

public class MoveButton extends Frame implements Runnable,ActionListener

{  【代码1】//用Thread类声明first,second两个线程对象

Button redButton,greenButton,startButton;

int distance=10;

MoveButton()

{  【代码2】 //创建first线程,当前窗口做为该线程的目标对象

【代码3】 //创建first线程,当前窗口做为该线程的目标对象

redButton=new Button();

greenButton=new Button();

redButton.setBackground(Color.red);

greenButton.setBackground(Color.green);

startButton=new Button("start");

startButton.addActionListener(this);

setLayout(null);

add(redButton);

redButton.setBounds(10,60,15,15);

add(greenButton);

greenButton.setBounds(100,60,15,15);

add(startButton);

startButton.setBounds(10,100,30,30);

setBounds(0,0,300,200);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{ public void windowClosing(WindowEvent e)

{ System.exit(0);

}

}

);

}

public void actionPerformed(ActionEvent e)

{  try{  first.start();

second.start();

}

catch(Exception exp){}

}

public void run()

{  while(true)

{  if(【代码4】) //判断当前占有CPU资源的线程是否是first

{   moveComponent(redButton);

try{ Thread.sleep(20);

}

catch(Exception exp){}

}

if(【代码5】) //判断当前占有CPU资源的线程是否是second

{   moveComponent(greenButton);

try{ Thread.sleep(10);

}

catch(Exception exp){}

}

}

}

public synchronized void moveComponent(Component b)

{

if(Thread.currentThread()==first)

{   while(distance>100&&distance<=200)

try{ wait();

}

catch(Exception exp){}

distance=distance+1;

b.setLocation(distance,60);

if(distance>=100)

{  b.setLocation(10,60);

notifyAll();

}

}

if(Thread.currentThread()==second)

{   while(distance>=10&&distance<100)

try{ wait();

}

catch(Exception exp){}

distance=distance+1;

b.setLocation(distance,60);

if(distance>200)

{  distance=10;

b.setLocation(100,60);

notifyAll();

}

}

}

}

MoveButtonMainClass.java

public class MoveButtonMainClass

{  public static void main(String args[])

{  new MoveButton();

}

  • 实验后的练习:

1. 在MoveButton类中再增加一个蓝色的按钮和一个third线程,third线程负责将这个蓝色的按钮从(200,60)运动到(300,60)。

《Java程序设计》

实验项目九  输入输出流

一、实验目的

1.掌握字符输入、输出流的用法;

2.掌握RandomAccessFil类的使用;

3.掌握ZipInputStream流的使用。

二、实验内容

实验1.学读汉字

  • 实验要求:

编写一个Java应用程序,要求如下:

(1)可以将一个由汉字字符组成的文本文件读入到程序中;

(2)单击名为“下一个汉字”的按钮,可以在一个标签中显示程序读入的一个汉字;

(3)单击名为“发音”的按钮,可以听到标签上显示的汉字的读音。

(4)用户可以使用文本编辑器编辑程序中用到的3个由汉字字符组成的文本文件:training1.txt、training2.txt和training.txt,这些文本文件中的汉字需要用空格、逗号或回车分隔。

()需要自己制作相应的声音文件,比如:training1.txt文件包含汉字“你”,那么在当前应用程序的运行目录中需要有“你.wav”格式的声音文件。

()用户选择“帮助”菜单,可以查看软件的帮助信息。

  • 程序模板

ChineseCharacters.java

import java.io.*;

import java.util.StringTokenizer;

public class ChineseCharacters

{  public StringBuffer getChinesecharacters(File file)

{  StringBuffer hanzi=new StringBuffer();

try{  FileReader  inOne=【代码1】

//创建指向文件f的inOne 的对象

BufferedReader inTwo=【代码2】

//创建指向文件inOne的inTwo的对象

String s=null;

int i=0;

while((s=【代码3】)!=null)   //inTwo读取一行

{StringTokenizer tokenizer=new StringTokenizer(s," ,'\n' ");

while(tokenizer.hasMoreTokens())

{  hanzi.append(tokenizer.nextToken());

}

}

}

catch(Exception e) {}

return hanzi;

}

}

StudyFrame.java

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import javax.sound.sampled.*;

public class StudyFrame extends Frame implements ItemListener,ActionListener,Runnable

{  ChineseCharacters chinese;

Choice choice;

Button getCharacters,voiceCharacters;

Label showCharacters;

StringBuffer trainedChinese=null;

Clip clip=null;

Thread voiceThread;

int k=0;

Panel pCenter;

CardLayout mycard;

TextArea textHelp;

MenuBar menubar;

Menu menu;

MenuItem help;

public StudyFrame()

{  chinese=new ChineseCharacters();

choice=new Choice();

choice.add("training1.txt");

choice.add("training2.txt");

choice.add("training3.txt");

showCharacters=new Label("",Label.CENTER);

showCharacters.setFont(new Font("宋体",Font.BOLD,72));

showCharacters.setBackground(Color.green);

getCharacters=new Button("下一个汉字");

voiceCharacters=new Button("发音");

voiceThread=new Thread(this);

choice.addItemListener(this);

voiceCharacters.addActionListener(this);

getCharacters.addActionListener(this);

Panel pNorth=new Panel();

pNorth.add(new Label("选择一个汉字字符组成的文件"));

pNorth.add(choice);

add(pNorth,BorderLayout.NORTH);

Panel pSouth=new Panel();

pSouth.add(getCharacters);

pSouth.add(voiceCharacters);

add(pSouth,BorderLayout.SOUTH);

pCenter=new Panel();

mycard=new CardLayout();

pCenter.setLayout(mycard);

textHelp=new TextArea();

pCenter.add("hanzi",showCharacters);

pCenter.add("help",textHelp);

add(pCenter,BorderLayout.CENTER);

menubar=new MenuBar();

menu=new Menu("帮助");

help=new MenuItem("关于学汉字");

help.addActionListener(this);

menu.add(help);

menubar.add(menu);

setMenuBar(menubar);

setSize(350,220);

setVisible(true);

addWindowListener(new WindowAdapter()

{  public void windowClosing(WindowEvent e)

{  System.exit(0);

}

});

validate();

}

public void itemStateChanged(ItemEvent e)

{  String fileName=choice.getSelectedItem();

File file=new File(fileName);

trainedChinese=chinese.getChinesecharacters(file);

k=0;

mycard.show(pCenter,"hanzi") ;

}

public void actionPerformed(ActionEvent e)

{  if(e.getSource()==getCharacters)

{  if(trainedChinese!=null)

{  char c=trainedChinese.charAt(k);

k++;

if(k>=trainedChinese.length())

k=0;

showCharacters.setText(""+c);

}

else

{ showCharacters.setText("请选择一个汉字字符文件");

}

}

if(e.getSource()==voiceCharacters)

{  if(!(voiceThread.isAlive()))

{ voiceThread=new Thread(this);

}

try{ voiceThread.start();

}

catch(Exception exp){}

}

if(e.getSource()==help)

{  mycard.show(pCenter,"help") ;

try{ File helpFile=new File("help.txt");

FileReader  inOne=【代码4】

//创建指向文件helpFile的inOne 的对象

BufferedReader inTwo=【代码5】

//创建指向文件inOne的inTwo 的对象

String s=null;

while((s=inTwo.readLine())!=null)

{  textHelp.append(s+"\n");

}

inOne.close();

inTwo.close();

}

catch(IOException exp){}

}

}

public void run()

{  voiceCharacters.setEnabled(false);

try{ if(clip!=null)

{ clip.close();

}

clip=AudioSystem.getClip();

File voiceFile=new File(showCharacters.getText().trim()+".wav");

clip.open(AudioSystem.getAudioInputStream(voiceFile));

}

catch(Exception exp){}

clip.start();

voiceCharacters.setEnabled(true);

}

}

StudyMainClass.java

public class StudyMainClass

{  public static void main(String args[])

{  new StudyFrame();

}

}

  • 实验后的练习:

1. 在StudyFrame类中增加一个按钮previousButton,单击该按钮可以读取前一个汉字。

实验2.统计英文单词

  • 实验要求:

使用RandomAccessFile流统计一篇英文中的单词,要求如下:

(1)一共出现了多少个单词;

(2)有多少个互不相同的单词;

(3)给出每个单词出现的频率,并将这些单词按频率大小顺序显示在一个TextArea中。

  • 程序模板

WordStatistic.java

import java.io.*;

import java.util.Vector;

public class WordStatistic

{ Vector allWorsd,noSameWord;

WordStatistic()

{  allWorsd=new Vector();

noSameWord=new Vector();

}

public void wordStatistic(File file)

{  try{  RandomAccessFile inOne=【代码1】

//创建指向文件file的inOne 的对象

RandomAccessFile inTwo=【代码2】

//创建指向文件file的inTwo 的对象

long wordStarPostion=0,wordEndPostion=0;

long length=inOne.length();

int flag=1;

int c=-1;

for(int k=0;k<=length;k++)

{   c=【代码3】        // inOne调用read()方法

boolean boo=(c<='Z'&&c>='A')||(c<='z'&&c>='a');

if(boo)

{  if(flag==1)

{  wordStarPostion=inOne.getFilePointer()-1;

flag=0;

}

}

else

{ if(flag==0)

{

if(c==-1)

wordEndPostion=inOne.getFilePointer();

else

wordEndPostion=inOne.getFilePointer()-1;

【代码4】

// inTwo调用seek方法将读写位置移动到wordStarPostion

byte cc[]=new byte[(int)wordEndPostion-(int)wordStarPostion];

【代码5】

// inTwo调用readFully(byte a)方法,向a传递cc

String word=new String(cc);

allWorsd.add(word);

if(!(noSameWord.contains(word)))

noSameWord.add(word);

}

flag=1;

}

}

inOne.close();

inTwo.close();

}

catch(Exception e){}

}

public Vector getAllWorsd()

{  return allWorsd;

}

public Vector getNoSameWord()

{  return noSameWord;

}

}

StatisticFrame.java

import java.awt.*;

import java.awt.event.*;

import java.util.Vector;

import java.io.File;

public class StatisticFrame extends Frame implements ActionListener

{  WordStatistic statistic;

TextArea showMessage;

Button openFile;

FileDialog  openFileDialog;

Vector allWord,noSameWord;

public StatisticFrame()

{ statistic=new WordStatistic();

showMessage=new TextArea();

openFile=new Button("Open File");

openFile.addActionListener(this);

add(openFile,BorderLayout.NORTH);

add(showMessage,BorderLayout.CENTER);

openFileDialog=new FileDialog(this,"打开文件话框",

FileDialog.LOAD);

allWord=new Vector();

noSameWord=new Vector();

setSize(350,300);

setVisible(true);

addWindowListener(new WindowAdapter()

{  public void windowClosing(WindowEvent e)

{  System.exit(0);

}

});

validate();

}

public void actionPerformed(ActionEvent e)

{  noSameWord.clear();

allWord.clear();

showMessage.setText(null);

openFileDialog.setVisible(true);

String fileName=openFileDialog.getFile();

if(fileName!=null)

{    statistic.wordStatistic(new File(fileName));

allWord=statistic.getAllWorsd();

noSameWord=statistic.getNoSameWord();

showMessage.append("\n"+fileName+"中有"

+allWord.size()+"个英文单词");

showMessage.append("\n其中有"+noSameWord.size()

+"个互不相同英文单词");

showMessage.append("\n按使用频率排列:\n");

int count[]=new int[noSameWord.size()];

for(int i=0;i<noSameWord.size();i++)

{  String s1=(String)noSameWord.elementAt(i);

for(int j=0;j<allWord.size();j++)

{   String s2=(String)allWord.elementAt(j);

if(s1.equals(s2))

count[i]++;

}

}

for(int m=0;m<noSameWord.size();m++)

{  for(int n=m+1;n<noSameWord.size();n++)

{ if(count[n]>count[m])

{  String temp=(String)noSameWord.elementAt(m);

noSameWord.setElementAt((String)noSameWord.elementAt(n),m);

noSameWord.setElementAt(temp,n);

int t=count[m];

count[m]=count[n];

count[n]=t;

}

}

}

for(int m=0;m<noSameWord.size();m++)

{  showMessage.append("\n"+(String)noSameWord.elementAt(m)+

":"+count[m]+"/"+allWord.size()+                                     "="+(1.0*count[m])/allWord.size());

}

}

}

}

StatisticMainClass.java

public class StatisticMainClass

{  public static void main(String args[])

{  new Statis ticFrame();

}

}

  • 实验后的练习:

1. 在StatisticFrame的showMessage中增加单词按字典序排序输出的信息。

实验3.读取Zip文件

  • 实验要求:

读取book.zip,并将book.zip中含有的文件重新存放到当前目录中的book文件夹中,即将book.zip的内容解压到book文件夹中。

  • 程序模板:

ReadZipFile.java

import java.io.*;

import java.util.zip.*;

public class ReadZipFile

{   public static void main(String args[])

{ File f=new File("book.zip");

File dir=new File("Book");

byte b[]=new byte[100];

dir.mkdir();

try

{ZipInputStream in=new ZipInputStream(new FileInputStream(f));

ZipEntry zipEntry=null;

while((zipEntry=in.getNextEntry())!=null)

{   File file=new File(dir,zipEntry.getName());

FileOutputStream out=new  FileOutputStream(file);

int n=-1;

System.out.println(file.getAbsolutePath()+"的内容:");

while((n=in.read(b,0,100))!=-1)

{ String str=new String(b,0,n);

System.out.println(str);

out.write(b,0,n);

}

out.close();

}

in.close();

}

catch(IOException ee)

{

System.out.println(ee);

}

}

}

  • 实验后的练习:

1. 编写一个GUI程序,提供1个对话框,用户可以使用这个对话框选择要解压缩的zip文件,设置解压后所得到的文件的存放目录。

《Java程序设计》

实验项目十  网络编程

一、实验目的

1. 学会使用URL对象;

2. 学会使用套接字读取服务器端的对象;

3. 掌握DatagramSocket类的使用。

二、实验内容

实验1.读取服务器端文件

  • 实验要求:

创建一个URL对象,然后让URL对象返回输入流,通过该输入流读取URL所包含的资源文件。

  • 程序模板:

ReadFile.java

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import java.io.*;

public class ReadURLSource

{  public static void main(String args[])

{  new NetWin();

}

}

class NetWin extends Frame implements ActionListener,Runnable

{  Button button;

URL url;

TextField text;

TextArea area;

byte b[]=new byte[118];

Thread thread;

NetWin()

{  text=new TextField(20);

area=new TextArea(12,12);

button=new Button("确定");

button.addActionListener(this);

thread=new Thread(this);

Panel p=new Panel();

p.add(new Label("输入网址:"));

p.add(text);

p.add(button);

add(area,BorderLayout.CENTER);

add(p,BorderLayout.NORTH);

setBounds(60,60,360,300);

setVisible(true);

validate();

addWindowListener(new WindowAdapter()

{   public void windowClosing(WindowEvent e)

{ System.exit(0);

}

});

}

public void actionPerformed(ActionEvent e)

{

if(!(thread.isAlive()))

thread=new Thread(this);

try{

thread.start();

}

catch(Exception ee)

{ text.setText("我正在读取"+url);

}

}

public void run()

{    try {    int n=-1;

area.setText(null);

String name=text.getText().trim();

【代码1】 //使用字符串name创建url对象

String hostName=【代码2】 //url调用getHost()

int urlPortNumber=【代码3】 //url调用getPort()

String fileName=【代码4】 //url调用getFile()

InputStream in=【代码5】 //url调用方法返回一个输入流

area.append("\n主机:"+hostName+"端口:"+urlPortNumber+

"包含的文件名字:"+fileName);

area.append("\n文件的内容如下:");

while((n=in.read(b))!=-1)

{   String s=new String(b,0,n);

area.append(s);

}

}

catch(MalformedURLException e1)

{     text.setText(""+e1);

return;

}

catch(IOException e1)

{     text.setText(""+e1);

return;

}

}

  • 实验后的练习:

1. public int getDefaultPort()、public String getRef()、public StringgetProtocol()等方法都是URL对象常有的方法,在模板中让url调用这些方法,并输出这些方法返回的值。

实验2.使用套接字读取服务器端对象

  • 实验要求:

客户端将服务器端的文本区对象读取到客户端,并添加到窗口中。首先将服务器端的程序编译通过,并运行,等待客户的呼叫。

  • 程序模板:

客户端模板:Client.java

import java.net.*;

import java.io.*;

import java.awt.*;

import java.awt.event.*;

class Client extends Frame implements Runnable,ActionListener

{  Button connection;

Socket socket=null;

ObjectInputStream in=null;

ObjectOutputStream out=null;

Thread thread;

public  Client()

{  socket=new Socket();

connection=new Button("连接服务器,读取文本区对象");

add(connection,BorderLayout.NORTH);

connection.addActionListener(this);

thread = new Thread(this);

setBounds(100,100,360,310);

setVisible(true);

addWindowListener(new WindowAdapter()

{ public void windowClosing(WindowEvent e)

{  System.exit(0);

}

}

);

}

public void run()

{  while(true)

{   try{  TextArea text=(TextArea)in.readObject();

add(text,BorderLayout.CENTER);

validate();

}

catch(Exception e)

{ break;

}

}

}

public void actionPerformed(ActionEvent e)

{ if(e.getSource()==connection)

{  try

{  if(socket.isConnected())

{

}

else

{

InetAddress  address=InetAddress.getByName("127.0.0.1");

InetSocketAddress socketAddress=【代码1】

//创建端口为4331、地址为address的socketAddress

【代码2】  //socket建立和socketAddress的连接呼叫。

in =new ObjectInputStream(【代码3】);

//socket返回输入流

out = new ObjectOutputStream(【代码4】);

//socket返回输出流

thread.start();

}

}

catch (Exception ee){}

}

}

public static void main(String args[])

{   Client win=new  Client();

}

}

服务器端模板:Server.java

import java.io.*;

import java.net.*;

import java.util.*;

import java.awt.*;

public class Server

{  public static void main(String args[])

{  ServerSocket server=null;

ServerThread thread;

Socket you=null;

while(true)

{  try{  server=【代码1】

//创建在端口4331上负责监听的 ServerSocket对象

}

catch(IOException e1)

{  System.out.println("正在监听");

}

try{  you=【代码2】

// server返回和客户端相连接的Socket对象

System.out.println("客户的地址:"+you.getInetAddress());

}

catch (IOException e)

{  System.out.println("正在等待客户");

}

if(you!=null)

{  new ServerThread(you).start();

}

else{  continue;

}

}

}

}

class ServerThread extends Thread

{  Socket socket;

ObjectInputStream in=null;

ObjectOutputStream out=null;

String s=null;

ServerThread(Socket t)

{  socket=t;

try  { out=new ObjectOutputStream(【代码3】);

//socket返回输出流。

in=new ObjectInputStream(【代码4】); //socket返回输入流。

}

catch (IOException e)

{}

}

public void run()

{  TextArea text=new TextArea("你好,我是服务器",12,12);

try{  out.writeObject(text);

}

catch (IOException e)

{   System.out.println("客户离开");

}

}

}

  • 实验后的练习:

1. 参照模板程序,编写一个客户/服务器程序,服务器向客户发送一个TextArea对象和一个Button对象。

实验3.基于UDP的图像传输

  • 实验要求:

编写客户/服务器程序,客户端使用DatagramSocket对象将数据包发送到服务器,请求获取服务器端的图像。服务器端将图像文件包装成数据包,并使用DatagramSocket对象将该数据包发送到客户端。首先将服务器端的程序编译通过,并运行起来,等待客户的请求。

  • 程序模板:

客户端模板:Client.java

import java.net.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

class ImageCanvas extends Canvas

{  Image image=null;

public ImageCanvas()

{  setSize(200,200);

}

public void paint(Graphics g)

{  if(image!=null)

g.drawImage(image,0,0,this);

}

public void setImage(Image image)

{  this.image=image;

}

}

class Client extends Frame implements Runnable,ActionListener

{  Button b=new Button("获取图像");

ImageCanvas canvas;

Client()

{  super("I am a client");

setSize(320,200);

setVisible(true);

b.addActionListener(this);

add(b,BorderLayout.NORTH);

canvas=new ImageCanvas();

add(canvas,BorderLayout.CENTER);

Thread thread=new Thread(this);

validate();

addWindowListener(new WindowAdapter()

{ public void windowClosing(WindowEvent e)

{ System.exit(0);

}

}

);

thread.start();

}

public void actionPerformed(ActionEvent event)

{  byte b[]="请发图像".trim().getBytes();

try{   InetAddress address=InetAddress.getByName("127.0.0.1");

DatagramPacket data=【代码1】

//创建数据包,该数据包的目标地址和端口分别是address和1234,其中的数据为数组b中的全部字节。

DatagramSocket mailSend=【代码2】

//创建负责发送数据的DatagramSocket对象。

【代码3】

// mailSend发送数据data。

}

catch(Exception e){}

}

public void run()

{  DatagramPacket pack=null;

DatagramSocket mailReceive=null;

byte b[]=new byte[8192];

ByteArrayOutputStream out=new ByteArrayOutputStream();

try{    pack=new DatagramPacket(b,b.length);

【代码4】

//创建在端口5678负责收取数据包的DatagramSocket对象。

}

catch(Exception e){}

try{   while(true)

{  mailReceive.receive(pack);

String message=new String(pack.getData(),0,pack.getLength());

if(message.startsWith("end"))

{  break;

}

out.write(pack.getData(),0,pack.getLength());

}

byte imagebyte[]=out.toByteArray();

out.close();

Toolkit tool=getToolkit();

Image image=tool.createImage(imagebyte);

canvas.setImage(image);

canvas.repaint();

validate();

}

catch(IOException e){}

}

public static void main(String args[])

{ new Client();

}

}

服务器端模板:Server.java

import java.net.*;

import java.io.*;

public class Server

{

public static void main(String args[])

{  DatagramPacket pack=null;

DatagramSocket mailReceive=null;

ServerThread thread;

byte b[]=new byte[8192];

InetAddress address=null;

pack=new DatagramPacket(b,b.length);

while(true)

{   try{  mailReceive=【代码1】

//创建在端口1234负责收取数据包的DatagramSocket对象。

}

catch(IOException e1)

{  System.out.println("正在等待");

}

try{   mailReceive.receive(pack);

address=【代码2】 //pack返回InetAddress对象。

System.out.println("客户的地址:"+address);

}

catch (IOException e) { }

if(address!=null)

{   new ServerThread(address).start();

}

else

{   continue;

}

}

}

}

class ServerThread extends Thread

{  InetAddress address;

DataOutputStream out=null;

DataInputStream  in=null;

String s=null;

ServerThread(InetAddress address)

{  this.address=address;

}

public void run()

{  FileInputStream in;

byte b[]=new byte[8192];

try{   in=new  FileInputStream ("a.jpg");

int n=-1;

while((n=in.read(b))!=-1)

{  DatagramPacket data=【代码3】

//创建数据包,目标地址和端口分别是address和5678,其中的数据为数组b中的前n个字节

DatagramSocket mailSend=【代码4】

//创建发送数据的DatagramSocket对象

【代码5】

// mailSend发送数据data

}

in.close();

byte end[]="end".getBytes();

DatagramPacket data=【代码6】

//创建数据包,目标地址和端口分别是address和5678,

其中的数据为数组end中的全部字节

DatagramSocket mailSend=【代码7】

//创建负责发送数据的DatagramSocket对象

【代码8】

// mailSend发送数据data

}

catch(Exception e){}

}

}

  • 实验后的练习:

1. 将上述模板程序改成用户从服务器获取一个文本文件的内容,并在客户端显示。

《Java程序设计》

部分参考代码

实验项目一 Java环境演练

实验1  一个简单的应用程序

【代码1】:  System.out.println("你好,很高兴学习Java") ;

【代码2】:  System.out.println("We are students") ;

实验2  一个简单的Java Applet程序

【代码1】:  g.drawString("这是一个Java Applet 程序",10,30);

【代码2】:  g.drawString("我改变了字体",20,100);

实验3  联合编译

【代码1】:  System.out.println("你好,只需编译我");

【代码2】:  System.out.println("I am A");

【代码3】:  System.out.println("I am B");

【代码4】:  System.out.println("I am  C");

实验项目二 基本数据类型与控制语句

实验1  输出希腊字母表

【代码1】: startPosition=(int)cStart;

【代码2】: endPosition=(int)cEnd ;

【代码3】: c=(char)i;

实验2  回文数

【代码1】: number<=99999&&number>=1

【代码2】: d5=number/10000;

【代码3】: d4=number%10000/1000;

【代码4】: d3=number%1000/100;

【代码5】: d5!=0

【代码6】: d1==d5&&d2==d4

【代码7】: d4!=0

【代码8】: d1==d4&&d2==d3

【代码9】: d3!=0

【代码10】:d1==d3

实验3  猜数字游戏

【代码1】: yourGuess!=realNumber

【代码2】: yourGuess>realNumber

【代码3】: yourGuess<realNumber

实验项目三 类与对象

实验1  三角形、梯形和圆形的类封装

【代码1】:   sideA=a;

sideB=b;

sideC=c;

【代码2】:  a+b>c&&a+c>b&&c+b>a

【代码3】:  boo=true;

【代码4】:  boo=false;

【代码5】:

if(boo)

{

length=sideA+sideB+sideC;

return length;

}

else

{

System.out.println("不是一个三角形,不能计算周长");

return 0;

}

【代码6】:  sideA=a;sideB=b;sideC=c;

【代码7】: a+b>c&&a+c>b&&c+b>a

【代码8】: boo=true;

【代码9】: boo=false;

【代码10】:

above=a;

bottom=b;

height=h;

【代码11】:

area=(above+bottom)/2*height;

return area;

【代码12】: radius=r;

【代码13】: return 3.14*radius*radius;

【代码14】: return 3.14*2*radius;

【代码15】: circle=new Circle(10);

【代码16】: trangle=new Trangle(3,4,5);

【代码17】: lader=new Lader(3,4,10);

【代码18】: length=circle.getLength();

【代码19】: area=circle.getArea();

【代码20】: length=trangle.getLength();

【代码21】: area=trangle.getArea();

【代码22】: area=lader.getArea();

【代码23】: trangle.setABC(12,34,1);

【代码24】: area=trangle.getArea();

【代码25】: length=trangle.getLength();

实验2  实例成员与类成员

【代码1】: float a;

【代码2】: static float b;

【代码3】: this.a=a;

【代码4】: this.b=b;

【代码5】: A.b=100;

【代码6】: A.inputB();

【代码7】: cat.setA(200);

【代码8】: cat.setB(400);

【代码9】: dog.setA(150);

【代码10】:dog.setB(300);

【代码11】:cat.inputA();

【代码12】:cat.inputB();

【代码13】:dog.inputA();

【代码14】:dog.inputB();

实验项目四 继承与接口

实验1  继承

1.答案:

【代码1】:  public void speakHello()

{

System.out.println("你好,吃饭了吗?");

}

【代码2】:

public void averageHeight()

{

height=173;

System.out.println("中国人的平均身高:"+height+"厘米");

}

【代码3】:

public void averageWeight()

{

weight=67.34;

System.out.println("中国人的平均体重:"+weight+"公斤");

}

【代码4】: System.out.println("坐如钟,站如松,睡如弓");

【代码5】:

public void speakHello()

{

System.out.println("How do You do");

}

【代码6】:

public void averageHeight()

{

height=188;

System.out.println("Amerian Average height:"+height+" cm");

}

【代码7】:

public void averageWeight()

{

weight=80.23;

System.out.println("Amerian Average weight:"+weight+" kg");

}

【代码8】: System.out.println("直拳、钩拳");

【代码9】:

public void speakHello()

{

System.out.println("您好");

}

【代码10】:

public void averageHeight()

{

height=16;

System.out.println("北京人的平均身高:"+height+"厘米");

}

【代码11】:

public void averageWeight()

{

weight=6;

System.out.println("北京人的平均体重:"+weight+"公斤");

}

【代码12】: System.out.println("京剧术语");

实验2  上转型对象

【代码1】:

public double earnings()

{

return 50000.456;

}

【代码2】:

public double earnings()

{

return 12*2300;

}

【代码3】:

public double earnings()

{

return 52*500;

}

【代码4】:

for(int i=0;i<employee.length;i++)

{

salaries=salaries+employee[i].earnings();

}

实验3 接口回调

【代码1】:

public double computeWeight()

{  return 45.5;

}

【代码2】:

public double computeWeight()

{  return 65.5;

}

【代码3】:

public double computeWeight()

{

return 145;

}

【代码4】:

for(int k=0;k<goods.length;k++)

{

totalWeights=totalWeights+goods[k].computeWeight();

}

实项目验五

实验一

【代码1】:  s1.equals(s2)

【代码2】:  s3.startsWith("220302")

【代码3】:  s4.compareTo(s5)>0

【代码4】:

【代码5】:  path.lastIndexOf("\\");

【代码6】:  path.substring(position+1);

【代码7】:  Integer.parseInt(s6);

【代码8】:  Double.parseDouble(s7);

【代码9】:  String.valueOf(m);

【代码10】:  s8.toCharArray();

实验二

【代码1】:  Calendar.getInstance();

【代码2】:  calendar.set(yearOne,monthOne-1,dayOne);

【代码3】:  calendar.getTimeInMillis();

【代码4】:  calendar.set(yearTwo,monthTwo-1,dayTwo);

【代码5】:  calendar.getTimeInMillis();

【代码6】:  new Date(timeOne);

【代码7】:  new Date(timeTwo);

【代码8】:   (Math.abs(timeTwo - timeOne)) / (1000 * 60 * 60 * 24);

实验三

【代码1】:  n1.add(n2);

【代码2】:  n1.subtract(n2);

【代码3】:  n1.multiply (n2);

【代码4】:  n1.divide(n2);

实验项目六 组件与事件处理(1)

实验一

【代码1】:  new TextField(10);

【代码2】:  new TextField(10);

【代码3】:  new TextField(10);

【代码4】:  getProblem.addActionListener(this);

【代码5】:  giveAnwser.addActionListener(this);

【代码6】:  textResult.addActionListener(this);

【代码7】:  e.getSource() == getProblem

【代码8】:  e.getSource() == giveAnwser

【代码9】:  new ComputerFrame("算术测试");

实验二

【代码1】:  new Choice();

【代码2】:  choice.add(itemRed);

【代码3】:  choice.add(itemYellow);

【代码4】:  choice.add(itemGreen);

【代码5】:  choice.addItemListener(this);

【代码6】:  choice.getSelectedItem();

实验3  布局与日历

【代码1】:  pCenter.setLayout(new GridLayout(7,7));

【代码2】:  pCenter.add(titleName[i]);

【代码3】:  pCenter.add(labelDay[i]);

【代码4】:  add(scrollPane,BorderLayout.CENTER);

【代码5】:  add(pNorth,BorderLayout.NORTH);

【代码6】:  add(pSouth,BorderLayout.SOUTH);

实验项目七 组件与事件处理(2)

实验1  方程求根

【代码1】:  controlButton.addActionListener(this);

【代码2】:  textA.getText()

【代码3】:  textB.getText()

【代码4】:  textC.getText()

实验2  字体对话框

【代码1】:  setModal(true);

【代码2】:  setVisible(false);

【代码3】:  setVisible(false);

【代码4】:  new FontDialog(this);

【代码5】:  dialog.setVisible(true);

【代码6】:  dialog.setTitle("字体对话框");

实验3  英语单词拼写训练

【代码1】:  addFocusListener(this);

【代码2】:  addMouseListener(this);

【代码3】:  label[k].addKeyListener(this);

【代码4】:  e.getKeyCode()==KeyEvent.VK_LEFT

【代码5】:  e.getKeyCode()==KeyEvent.VK_RIGHT

实验项目八 多线程

实验1  汉字打字练习

【代码1】:  sleep(6000);

【代码2】:  WordThread giveWord;

【代码3】:  giveWord=new WordThread(wordLabel);

【代码4】:  giveWord.isAlive()

【代码5】:  giveWord.start();

实验2  旋转的行星

【代码1】:  Thread moon;

【代码2】:  moon=new Thread(this);

【代码3】:  Thread.sleep(10);

【代码4】:  Thread rotate;

【代码5】:  rotate.start();

实验3  双线程接力

【代码1】:  Thread first,second;

【代码2】:  first=new Thread(this);

【代码3】:  second=new Thread(this);

【代码4】:  Thread.currentThread()==first

【代码5】:  Thread.currentThread()==second

实验项目九 输入输出流

实验1  学读汉字

【代码1】:  new FileReader(file);

【代码2】:  new BufferedReader(inOne);

【代码3】:  inTwo.readLine()

【代码4】:  new FileReader(helpFile);

【代码5】:  new BufferedReader(inOne);

实验2  统计英文单词字

【代码1】:  new RandomAccessFile(file,"rw");

【代码2】:  new RandomAccessFile(file,"rw");

【代码3】:  inOne.read();

【代码4】:  inTwo.seek(wordStarPostion);

【代码5】:  inTwo.readFully(cc);

实验项目十 网络编程

实验1  读取服务器端文件

【代码1】:  url=new URL(name);

【代码2】:  url.getHost();

【代码3】:  url.getPort();

【代码4】:  url.getFile();

【代码5】:  url.openStream();

实验2  使用套接字读取服务器端对象

客户端模板:Client.java答案:

【代码1】:  new InetSocketAddress(address,4331);

【代码2】:  socket.connect(socketAddress);

【代码3】:  socket.getInputStream()

【代码4】:  socket.getOutputStream()

服务器端模板:Server.java答案:

【代码1】:  new ServerSocket(4331);

【代码2】:  server.accept();

【代码3】:  socket.getOutputStream()

【代码4】:  socket.getInputStream()

实验3  基于UDP的图像传输

客户端模板:Client.java答案:

【代码1】:  new DatagramPacket(b,b.length,address,1234);

【代码2】:  new DatagramSocket();

【代码3】:  mailSend.send(data);

【代码4】:  mailReceive=new DatagramSocket(5678);

服务器端模板:Server.java答案:

【代码1】:  new DatagramSocket(1234);

【代码2】:  pack.getAddress();

【代码3】:  new DatagramPacket(b,n,address,5678);

【代码4】:  new DatagramSocket();

【代码5】:  mailSend.send(data);

【代码6】:  new DatagramPacket(end,end.length,address,5678);

【代码7】:  new DatagramSocket();

【代码8】:  mailSend.send(data);

《Java程序设计》

参考文献

[1] 张跃平,耿祥义.Java 2 实用教程(第三版)[M]. 清华大学出版社,2006.8.

[2] 张跃平,耿祥义.Java 2 实用教程(第三版)实验指导与习题解答[M]. 清华大学出版社,2006.8.

[3] Bruce Eckel. Java编程思想[M]. 机械工业出版社,2007.6.

[4] 孙鑫. Java Web开发详解:XML+DTD+XML Schema+XSLT+Servlet 3.0+JSP2.2深入剖析与实例应用[M]. 电子工业出版社,2012.5.

[5] 施霞萍.Java程序设计教程[M]. 机械工业出版社,2012.11.

《Java 2 实用教程》课程学习(17)——《Java 程序设计》实验指导书-校内实验教材相关推荐

  1. java实验指导书(实验四)答案_java程序设计实验指导书答案

    ? 狗生活在陆地上(是一种陆生动物),既是哺乳类的也是肉食性的.狗通常的时候和人 打招呼会通过"摇摇尾巴",在被抚摸感到舒服的时候,会"旺旺叫",而在受到惊吓情 ...

  2. java web编程技术解题与实验指导_javaweb编程技术实验指导书

    javaweb编程技术实验指导书 <Java Web编程技术> 实 验 指 导 书 沈泽刚 编写2010 年 3 月目 录 实验一 简单的 Servlet 与 JSP .1 实验二 HTT ...

  3. java web编程技术上机实验_JavaWeb編程技术实验指导书.doc

    JavaWeb編程技术实验指导书 <Java Web编程技术> 实 验 指 导 书 沈泽刚 编写 2010年3月 目 录 实验一 简单的Servlet与JSP1 实验二 HTTP请求对象3 ...

  4. java计算机毕业设计英语课程学习网站源码+数据库+系统+lw文档+mybatis+运行部署

    java计算机毕业设计英语课程学习网站源码+数据库+系统+lw文档+mybatis+运行部署 java计算机毕业设计英语课程学习网站源码+数据库+系统+lw文档+mybatis+运行部署 本源码技术栈 ...

  5. (尚硅谷java零基础教程)学习笔记day7/8-数组

    1.数组的概述 1.1 定义 数组(Array),是多个相同类型数据按一定顺序排列的集合,并使用一个名字命名,并通过编号的方式对这些数据进行统一管理. 1.2 数组的相关概念 数组名 元素 数组的索引 ...

  6. Java 2 实用教程

    Java 2 实用教程 :

  7. 《Java 2实用教程》(第5版)(清华大学出版社)作者:张跃平、耿祥义习题答案详解

    <Java 2实用教程>(第5版)(清华大学出版社)作者:张跃平.耿祥义习题答案详解 **此答案与详解是本人做作业时所写部分答案,如有错误之处请指出 ** 习题2 1.问答题 (3) 逻辑 ...

  8. Java 2实用教程(第三版)实验指导与习题解答and实验模版代码及答案 (二)

    实验2 字体对话框 1.答案: [代码1]:setModal(true); [代码2]:setVisible(false); [代码3]:setVisible(false); [代码4]:new Fo ...

  9. Java NIO系列教程(十) Java NIO DatagramChannel

    转载自  Java NIO系列教程(十) Java NIO DatagramChannel 译文链接    作者:Jakob Jenkov    译者:郑玉婷     校对:丁一 Java NIO中的 ...

最新文章

  1. 985博士:导师是院士,直到毕业,我们都没单独说过一句话
  2. camel in action
  3. An Openfire plugin for Webspell sites.
  4. 读写分离的适用场景(转载)
  5. python加载html表格数据,使用python 3.6获取html表格行数据美丽的汤
  6. android动画影子效果,Android TV常用动画的效果,View选中变大且有阴影(手机也能用)...
  7. jquery工具方法parseJSON
  8. 【英语学习】【English L06】U05 Appointments L2 I'd like to make an airport shuttle service reservation
  9. .NET/Dot Net学习笔记---.net理解,C#.net的基本类型,字符串转义字符处理..
  10. 《OSPF和IS-IS详解》
  11. 181221每日一句
  12. 重构实例-消息发送-原始代码及准备-1
  13. python实现简单舒尔方格
  14. android 自定义view 动画效果,Android自定义view实现阻尼效果的加载动画
  15. 基于51单片机的倒计时温度检测报警器
  16. grep -e 和 grep -E 的区别是什么?
  17. 解锁网易云音乐小工具_什么?网易云音乐又变灰了
  18. Arduino初初教程7——模拟量采集
  19. 【Python】浮点数精度问题(包含解决方案)
  20. 操作系统——动态分配算法(首次适应算法,最佳适应算法,最坏适应算法及回收)

热门文章

  1. 时间序列论文:Multi-Scale Convolutional Neural Networks
  2. 【matplotlib复杂的频数分布直方图】多子图,共享横纵坐标名,横坐标位置居中及标签显示,显示每个bar的频数
  3. 由己方的a网站跳转第三方的b网站
  4. [RK3399][Android7.1] 调试笔记 --- 解决开关按键时产生的Pop声
  5. 政府采购:国产软件发展的第一推动力
  6. Doodle era
  7. CSS文本溢出用...显示
  8. 一下子搞懂JDBC,看这篇就够了--以MySQL为例。
  9. pinctrl和gpio子系统
  10. 40大妈学计算机,扒鸡大妈震撼最强大脑评委网友:你是计算机吗