Java 2实用教程(第三版)实验指导与习题解答and实验模版代码及答案 (二)

时间:2022-01-02 11:51:19

实验2 字体对话框

1.答案:

【代码1】:setModal(true);

【代码2】:setVisible(false);

【代码3】:setVisible(false);

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

【代码5】:setVisible(true);

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

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();

}

}

实验3 英语单词拼写训练

1.答案:

【代码1】:addFocusListener(this);

【代码2】:addMouseListener(this);

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

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

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

2.模板代码

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].getText();

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

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].getText();

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

label[index+1].setText(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].getText();

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();

}

}

上机实践8多线程

实验1 汉字打字练习

1.答案:

【代码1】:sleep(6000);

【代码2】:WordThread giveWord;

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

【代码4】:giveWord.isAlive()

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

2.模板代码

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);

}

}

}

WordThread.java

public class ThreadWordMainClass

{ public static void main(String args[])

{ new ThreadFrame();

}

实验2 旋转的行星

1.答案:

【代码1】:Thread moon;

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

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

【代码4】:Thread rotate;

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

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);

}

}

HaveThreadFrame.java

public class ThreadRotateMainClass

{ public static void main(String args[])

{ new HaveThreadFrame();

}

}

实验3 双线程接力

1.答案:

【代码1】:Thread first,second;

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

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

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

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

2.模板代码

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();

}

上机实践9输入输出流

实验1 学读汉字

1.答案:

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

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

【代码3】:inTwo.readLine();

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

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

2.模板代码

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();

}

}

实验2 统计英文单词字

1.答案:

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

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

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

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

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

2.模板代码

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;

}

}

RandomExample.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());

}

}

}

}

RandomExample.java

public class StatisticMainClass

{ public static void main(String args[])

{ new StatisticFrame();

}

}

实验2 读取Zip文件

1.模板代码

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);

}

}

}

上机实践10Java 中的网络编程

实验1 读取服务器端文件

1.答案:

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

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

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

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

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

2.模板代码

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;

}

}

实验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()

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("客户离开");

}

}

}

实验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);

2.模板代码

客户端模板: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){}

}

}

上机实践11数据结构