还剩47页未读,继续阅读
本资源只提供10页预览,全部文档请下载后查看!喜欢就下载吧,查找使用更方便
文本内容:
习题解答习题(第章)11
一、问答题
1.James Gosling1)
2.需3个步骤2)用文本编辑器编写源文件3)使用javac编译源文件,得到字节码文件4)使用解释器运行程序源文件由若干个类所构成对于应用程序,必须有一个类含有(
3.public staticvoid mainString)的方法,含有该方法的类称为应用程序的主类不一定,但至多有一个类args[]public
4.set classpath=D:\jdk\jre\lib\rt.jar;.;和
5.java class
6.jav.Bir..独行风格(大括号独占行)和行尾风格(左大扩号在上一行行尾,右大括号独占行)
二、选择题
7.
1.Bo
2.Do
三、阅读程序()()两个字节码,分另是
1.a Person.javao bUPerson.class,和()得至〉得到Xiti.classo c“NoSuchMethodError”u,得到“您好,很高兴NoClassDefFoundError:Xiti/class认识您nice tomeet you”习题(第章)22
一、问答题
1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符标识符由字母、下划线、美元符号和数字组成,第一个字符不能是数字不是标识符falsepublic classExample5_13{public staticvoid mainString args[]{Simulator simulator=new Simulator;simulator.playSoundnew Dog;simulator.playSoundnew Cat;习题(第章)77
一、问答题i.有效
2.可以
3.不可以
4.一定是
二、选择题
1.Co
2.Co
三、阅读程序大家好,祝工作顺利!
1.是接口变量
2.p你好
3.fine thankso属于上机实习程序,解答略
4.
四、编程题import java.util.*;public classE{public staticvoid mainString args[]{Scanner reader=new ScannerSystem.in;double sum=0;int m=0;数据不合理”;whilereader.hasNextDouble{double x=reader.nextDouble;assert x100:m=m+1;sum=sum+x;}System.out.printfn%d个数的和为%f\n”,m,sum;System.out.printfn%d个数的平均值是%1\#,01,$11111/111;习题(第章)88
一、问答题
1.不是1\hell是是
2.4和3o
3.false和trueo
4.负数
5.是trueo
6.3和-
17.会发生NumberFormatException异常
二、选择题l.Ao
2.Co
3.Bo
4.Do
5.Co
三、阅读程序【代码】苹果
1..【代码】2Love:Game[代码[代码我们
3.1]:152]:abc【代码】
4.13579o
5.【代码】:9javaHellOo
6.属于上机实习程序,解答略
7.属于上机实习程序,解答略
四、编程题
1.public classE{public staticvoid mainString args[]{String sl,s2,tl=nABCDabcdH;s1=t
1.toUpperCase;s2=tl.toLowerCase;System.out.printlns1;System.out.printlns2;String s3=sl.concats2;System.out.printlns3;2・.publi.clas・・{public staticvoid mainString args[]{String s=nABCDabcdn;char cStart=s.charAtO;char cEnd=s.charAts.length-1;System.out.printlncStart;System.out.printlncEnd;}3・・impor・java・util・*;public classE{public staticvoid mainString args[J{int yearl,month1,day1,year2,month2,day2;try{yearl=lnteger.parselntargs[];month l=lnteger.parselntargs
[1];dayl=lnteger.parselntargs
[2];year2=lnteger.parselntargs
[3];month2=lnteger.parselntargs
[4];day2=lnteger.parselntargsf5];}catchNumberFormatException e{yearl=2012;month1=0;day1=1;year2=2018;month2=0;day2=l;Calendar calendai-Calendar.getInstance;calendar.sety ear1,month1-1,day1;long timeYearl=calendar.getTimeInMillis;calendar.setyear2,month2-1,day2;long timeYear2=calendar.getTimeInMillis;相隔天数二long Math.abstimeYearl-timeYear2/1000*60*60*24年月”日和”+System.out.println”+yearl+“+month I+“+day1+”年”月”日相隔”+相隔天数+”year2+“+month2+“+day2+“天4・・impor・java・utiL*;public classE{public staticvoid mainString argslJ{double a=,b=,c=;a=12;b=24;c=Math.asin
0.56;System.out.printlnc;c=Math.cos
3.14;System.out.printlnc;二⑴;c Math.expSystem.out.printlnc;c=Math.log8;System.out.printlnc;
5.public classE{public staticvoid mainString args[J{String str=nabl23you你是谁?”;String regex=\\D+”;str=str.replaceAllregex,,M,;System.out.printlnstr;
6.import java.util.*;public classE{public staticvoid mainString args[J{”数学分,物理分,英语分”;String cost=877696二Scanner scannernew Scannercost;scanner.useDelimitern[AO
123456789.]+;double sum=0;int count=0;whilescanner.hasNext{二try{double scorescanner.nextDouble;count++;sum=sum+score;System.out.printlnscore;}catchInputMismatchException exp{String t=scanner.next;总分:“”分System,out.printin+sum+平均分:“分”;System,out.printing+sum/count+“习题(第章)99
一、问答题
1.Frame容器的默认布局是BorderLayout布局
2.不可以
3.ActionEvento
4.DocumentEvento
5.5个
6.MouseMotionListenero
二、选择题
1.Co
2.Ao
3.Ao
4.Do
5.Co
三、编程题
1.import java.awt.*;import javax.swing.event.*;import javax.swing.*;import java.awt.event.*;public classE{public staticvoid mainStringargsf]{Computer fr=new Computer;class Computerextends JFrame implements DocumentListener{JTextArea text1,text2;int count=l;double sum=0,aver=0;Computer{setLayoutnew FlowLayout;textl=new JTextArea6,20;text2=new JTextArea6,20;addnew JScrollPanetextl;addnew JScrollPanetext2;text
2.setEditablefalse;text
1.getDocument.addDocumentListenerthis;setSize300,320;setVisibletrue;validate;setDefaultCloseOperationJFrame.DISPOSE_ON_CLOSE;public voidchangedUpdateDocumentEvent e{String s=textl.getText;String[]a=s.splitn[A
0123456789.]+n;sum=0;aver=0;〈』forint i=O;i aength;i++{try{sum=sum+Double.parseDoublea[iJ;}catchException ee{}aver=sum/count;text
2.setTextnull;text
2.appendH\n和:+sum;text
2.appendH\n平均值:n+aver;}public voidremoveUpdateDocumentEvent e{changedUpdatee;public voidinsertUpdateDocumentEvent e{changedUpdatee;
2..impor.java.awt.*;import javax.swing.event.*;import javax.swing.*;import java.awt.event.*;public classE{public staticvoid mainStringargsLJ{ComputerFrame fr=new ComputerFrame;class ComputerFrameextends JFrame implements ActionListener{JTextFieldtextl,text2,text3;JButton buttonAdd,buttonSub,buttonMul,buttonDiv;JLabel label;public ComputerFrame{setLayoutnew FlowLayoutO;textl=new JTextFieldlO;text2=new JTextFieldlO;text3=new JTextFieidl0;label=new JLabelnH JLabel.CENTER;label.setBackgroundColor.green;addtextl;addlabel;addtext2;addtext3;“加;buttonAdd=new JButton减”;buttonSub=new JButton“乘;除;buttonMul=new JButtonbuttonDiv=new JButtonaddbuttonAdd;addbuttonSub;addbuttonMul;addbuttonDiv;buttonAdd.addActionListenerthis;buttonSub.addActionListener this;buttonMul.addActionListenerthis;buttonDiv.addActionListenerthis;setSize300,320;setVisibletrue;validate;setDefaultCloseOperationJFrame.DISPOSE_ON_CLOSE;public voidactionPerformedActionEvent e{double n;ife.getSource==buttonAdd{double nl,n2;try{nl=Double.parseDoubletextl.getText;n2=Double.parseDoubletext
2.getText;n=nl+n2;text
3.setTextString.valueOfn;labeLsetTextC^1;catchNumberFormatException ee请输入数字字符{text
3.setTextelse ife.getSource==buttonSub{double nl,n2;try{nl=Double.parseDoubletextl.getText;n2=Double.parseDoubletext
2.getText;n=nl-n2;text
3.setTextString.valueOfn;label.setTextn-n;catchNumberFormatException ee请输入数字字符{text
3.setText}else ife.getSource==buttonMul{double nl,n2;try{nl=Double.parseDoubletextl.getText;n2=Double.parseDoubletext
2.getText;n=nl*n2;text
3.setTextString.valueOfn;label.setTextn*n;}catchNumberFormatException ee请输入数字字符{text
3.setTextelse ife.getSource==buttonDiv{double nl,n2;try{nl=Double.parseDoubletextl.getText;n2=Double.parseDoubletext
2.getText;n=nl/n2;text
3.setTextString.valueOfn;label.setText7H;catchNumberFormatException ee请输入数字字符{text
3.setText validate;
3..impor.java.awt.*;import java.awt.event.*;import javax.swing.*;public classE{public staticvoid mainStringargs[]{Window win=new Window;使用结构win.setTitle MVCwin.setBoundsl00,100,420,260;class Windowextends JFrameimplements ActionListener{//模型Lader lader;〃视图JTextField textAbove,textBottom,textHeight;〃视图JTextArea showArea;//控制器JButton controlButton;Window{init;setVisibletrue;setDefaultCloseOperationJFrame.EXIT_ON_CLOSE;void init{lader=new Lader;textAbove=new JTextField5;二textBottom new JTextField5;textHeight=newJTextField5;show Area=new JTextArea;计算面积controlButton=new JButtonJPanelpNorth=new JPanel;上底:;pNorth.addnew JLabelpNorth.addtextAbove;pNorth.addnew JLabel下底:;pNorth.addtextBottom;高:;pNorth.addnew JLabelpNorth.addtextHeight;pNorth.addcontrolButton;controlButton.addActionListenerthis;addpNorth,BorderLayout.NORTH;addnew JScrollPaneshowArea,BorderLayout.CENTER;public voidactionPerformedActionEvent e{trydouble above=Double.parseDoubletextAbove.getText.trim;double bottom=Double.parseDoubletextBottom.getText.trim;double height=Double.parseDoubletextHeight.getText.trim;lader.setAboveabove;lader.setBottombottom;lader.setHeightheight;double area=lader.getArea;面积:show Area.append+area+\n;catchException ex{showArea.append,\n,+ex4-H\nn;class Lader{double above,bottom,height;public doublegetArea{double area=above+bottom*height/
2.;return area;public voidsetAbovedouble a{above=a;public voidsetBottomdouble b{bottom=b;public voidsetHeightdouble c{height=c;习题第章1010
一、问答题
1.使用FilelnputStreamo
2.FilelnputStream按字节读取文件,FileReader按字符读取文件
3.不可以
4.使用对象流写入或读入对象时,要保证对象是序列化的
5.使用对象流很容易得获取一个序列化对象的克隆,只需将该对象写入到对象输出流,那么用对象输入流读回的对象一定是原对象的一个克隆
二、选择题
1.Co
2.Bo
三、阅读程序
1.【代码1】51【代码2]【代码】【代码】【代码】【代码】
2.132abc314dbco上机实习题,解答略
3.
四、编程题
1.import java.io.*;public classE{public staticvoid mainStringargs[]{File f=new FilenE.javaH;;try{RandomAccessFile random=new RandomAccessFilef,urwn;random.seekO;long m=random.length;whilem=0{m=m-l;random,seekm;int c=random.readByte;ifc=255c=0System.out.printcharc;else{random.seekm;byte cc[J=new byte[2J;random.readFullycc;System.out.printnew Stringcc;catchException exp{}关键字就是语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来
2.Java用和不是关键字个关键字true false6class implementsinterface enumextendsabstract o
3.boolean,char,byte,short,int,long,float,doubleo常量必须用或为后缀常量用或为后缀,但允许省略后缀
4.mat Ff doubleD d一维数组名二维数组名
5..length length
二、选择题【代码】【代码】【代码】【代码
1.Co
2.ADFo
3.Bo
4.BE
5.2345]
6.B
三、阅读或调试程序属于操作题,解答略
1.属于操作题,解答略
2.属于操作题,解答略
3.
4.【代码1】4【代码2]b
[0]=l【代码】【代码】
5.14027
四、编写程序
1.publi.clas..{public staticvoid mainStringargs[]{你;System.out.printlnintSystem.out.printlnint,1Jc,;他;System,out.printlnint2・・publi・clas.・{public staticvoid mainStringargs[]{char cStart-a\cEnd-co1;forchar c=cStart;c=cEnd;c++System.out.printn n+c;习题(第章)33
一、问答题
1.boolean不可以
2.
3.boolean.不是必须的4结束语句的执行
5.while可以
6.
2.・impor・java・io.*;public classE{public staticvoid mainStringargsf]{File file=new FilenE.javan;File tempFile=new Filentemp.txtn;try{FileReader inOne=new FileReaderfile;BufferedReader inTwo=new B ufferedReaderinOne;二FileWriter tofilenew FileWritertempFile;Buffered Writerout=new Buffered Writertofi1e;String s=null;int i=0;s=inTwo.readLine;whiles!=null{i++;out.writei+n n+s;out.newLine;s=inTwo.readLine;inOne.close;inTwo.close;out.flush;out.close;tofile.close;catchIOException e{}}
3..impor.java.io.^;import java.util.*;public classE{public staticvoid mainStringargs[]{File file=new Filena.txtn;Scanner sc=null;double sum=0;int count=0;try{sc=new Scannerfile;sc.useDelimiterC[A
0123456789.]+H;whilesc.hasNext{二try{double pricesc.nextDouble;count++;sum=sum+price;System.out.printlnprice;catchInputMismatchException exp{String t=sc.next;平均价格:“System,out.printin+sum/count;catchException exp{System.out.printlnexp;习题(第章)1111
一、问答题
1.在MySQL安装目录的bin子目录下键入mysqld或mysqld-nt启动MySQL数据库服务器
2.复制到JDK的扩展目录中(即JAVA_HOME环境变量指定的JDK,见第1章的
1.
3.3),比如:E:\jdkl.8\jre\lib\exto
3.减轻数据库内部SQL语句解释器的负担
4.事务由一组SQL语句组成,所谓事务处理是指应用程序保证事务中的SQL语句要么全部都执行,要么一个都不执行事务处理步骤是调用
(1)连接对象用setAutoCommit方法关闭自动提交模式,
(2)连接对象用commit方法处理事务,
(3)连接对象用rollback方法处理事务失败
二、编程题.同时用到了例子中的类12GetDBConnectionimport java.sql.*;import java.sql.*;public classBianChengl{()public staticvoid mainStringargs[J{Connection con;Statement sql;ResultSet rs;con=GetDBConnection.connectDB(nstudents,V,rootV,n);()if con==null return;String sqlStr=select*from messorder bybirthday1;(trysql=con.createStatement;二rs sqLexecuteQuerysqlStr;whilers.next{String number=rs.getString1;String name=rs.getString2;Date date=rs.getDate3;float height=rs.getFloat4;System.out.printfn%s\tn,number;System.out.printf,%s\tn,name;System.out.printfn%s\tn,date;System.out.printfn%.2f\nn,height;con.closeQ;catchSQLException e{System.out.printlne;时用到了例子中的类
2.
1.6Queryimport javax.swing.*;public classBianCheng2{public staticvoid mainStringargsLJ{String[]tableHead;String LJ[J content;JTable table;JFrame win=new JFrame;Query findRecord=new Query;findRecord.setDatabaseNameargs[OJ;findRecord.setSQLnselect*from n+args[lJ;content=findRecord.getRecord;tableHead=findRecord.getColumnName;table=new JTablecontent,tableHead;win.addnew JScrollPanetable;win.setBoundsl2,100,400,200;win.setVisibletrue;win.setDefaultCloseOperationJFrame.EXIT_ON_CLOSE;习题(第章)1212
一、问答题种状态新建、运行、中断和死亡
1.
42.有4种原因的中断
(1)JVM将CPU资源从当前线程切换给其他线程,使本线程让出CPU的使用权处于中断状态()线程使用资源期间,执行了()方法,使当前2CPU sleepint millsecond线程进入休眠状态
(3)线程使用CPU资源期间,执行了wait方法,使得当前线程进入等待状态
(4)线程使用CPU资源期间,执行某个操作进入阻塞状态,比如执行读/写操作引起阻塞死亡状态,不能再调用方法
3.start新建和死亡状态
4.两种方法用类或其子类
5.Thread使用()方法
6.setPrority intgrade使我们可以创建多个线程,在处理多线程问题时,我们必须注意这样一个问题当两个或多
7.Java个线程同时访问同一个变量,并且一个线程需要修改这个变量我们应对这样的问题作出处理,否则可能发生混乱当一个线程使用的同步方法中用到某个变量,而此变量又需要其它线程修改后才能符合本线程的
8.需要,那么可以在同步方法中使用方法使用方法可以中断方法的执行,使本线程等待,wait wait暂时让出的使用权,并允许其它线程使用这个同步方法其它线程如果在使用这个同步方法时CPU不需要等待,那么它使用完这个同步方法的同时,应当用方法通知所有的由于使用这个notifyAHO同步方法而处于等待的线程结束等待不合理
9.“吵醒”休眠的线程一个占有资源的线程可以让休眠的线程调用方法“吵醒”
10.CPU interrupt自己,即导致休眠的线程发生异常,从而结束休眠,重新排队等待资源InterruptedException CPU
二、选择题
1.A©
2.A
3.B0
三、阅读程序属于上机调试题目,解答略
1.属于上机调试题目,解答略
2.属于上机调试题目,解答略
3.属于上机调试题目,解答略
4.属于上机调试题目,解答略
6.属于上机调试题目,解答略
5.属于上机调试题目,解答略
8.【代码】
7.BA
四、编写程序
1.publi.clas..{public staticvoid mainStringargs[]{Cinema a=new Cinema;a.zhang.start;a.sun.start;a.zhao.start;〃负责卖票的类class TicketSeller{int fiveNumber=3,tenNumber=0,twentyNumber=0;public synchronizedvoid sellTicketintreceiveMoney{ifreceiveMoney==5{fiveNumber=fiveNumber+1;”给我元钱,这是您的张入场卷System.out.printlnThread.currentThread.getName+51else ifreceiveMoney=10{whilefiveNumber1靠边等”;{try{System.out.printlnThread.cuirentThreadO.getName+”wait;结束等待System.out.printlnThread.cuirentThread.getName+”catchInterruptedException e{}fiveNumber=fiveNumber-1;tenN umber=tenN umber+1;”给我元钱,找您元,这是您的System.out.printlnThread.currentThread.getName+105张入场卷1else ifreceiveMoney=20{whilefiveNumber l||tenNumber1{try{System.out.printlnThread.currentThread.getName4-nSiil^n;wait;System.out・printlnThread.cuITentThread・getName+结束等待;catchInterruptedException e{}fiveNumber=fiveNumber-1;tenNumber=tenNumber-1;twentyNumber=twentyNumber+1;System.out.printlnThread.currentThread.getName+”给元钱,找您一张元和一张元,这是您的张入场卷205101notifyAHQ;class Cinemaimplements Runnable{Thread zhang,sun,zhao;TicketSeller seller;Cinema{zhang=new Threadthis;sun=new Threadthis;zhao=new Threadthis;张小有”;zhang.setName“孙大名;sun.setName“赵中堂”;zhao.setNameseller=new TicketSeller;public voidrun{ifThread.currentThread==zhang{seller.sellTicket20;else ifThread.currentThread==sun{seller.sellTicketlO;else ifThread.currentThread==zhao{seller.sellTicket5;}2参照本章例子.6参照本章例子
3.9习题第章1313
一、问答题
1.一个URL对象通常包含最基本的三部分信息协议、地址、资源
2.URL对象调用InputStream openStream方法可以返回一个输入流,该输入流指向URL对象所包含的资源通过该输入流可以将服务器上的资源信息读入到客户端
3.客户端的套接字和服务器端的套接字通过输入、输出流互相连接后进行通信
4.使用方法accept,accept会返回一个和客户端Socket对象相连接的Socket对象accept方法会堵塞线程的继续执行,直到接收到客户的呼叫
5.域名/IP
四、编程题客户端
1.1importjava.net.*;import java.io.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;public classClient{public staticvoid mainStringargs[]{new ComputerClient;class ComputerClientextends Frameimplements Runnable,ActionListener{Button connection,send;TextField inputText,showResult;二Socket socketnull;DatalnputStream in=null;DataOutputStream out=null;Thread thread;ComputerClient{socket=new Socket;setLayoutnew FlowLayout;Box box=Box.createVerticalBox;连接服务器;connection=new Button发送send=new Buttonsend.setEnabledfalse;inputText=new TextField12;showResult=new TextField12;box.addconnection;输入三角形三边的长度,用逗号或空格分隔:;box.addnew Labelbox.addinputText;box.addsend;收到的结果”;box.addnew Label,box.addshowResult;connection.addActionListener this;send.addActionListenerthis;thread=new Threadthis;addbox;setBoundsl0,30,300,400;setVisibletrue;validate;addWindowListenernew WindowAdapter{public voidwindowClosingWindowEvent e{System.exitO;};public voidactionPerformedActionEvent e{ife.getSource==connection〃请求和服务器建立套接字连接{try{ifsocket.isConnected{else{InetAddress address=InetAddress.getByNameH
127.
0.
0.1n;InetSocketAddress socketAddress=new InetSocketAddressaddress,4331;socket.connectsocketAddress;in=new DataInputStreamsocket.getInputStream;out=new DataOutputStreamsocket.getOutputStream;send.setEnabled true;thread.start;catch lOExceptionee{}ife.getSource==send{String s=inputText.getText;ifs!=null{try{out.writeUTFs;catchIOException el{}public voidrun{String s=null;whiletrue{try{s=in.readUTF;showResult.setTexts;catchIOException e与服务器已断开{showResult.setText break;服务器端2import java.io.*;importjava.net.*;import java.util.*;public class Server{public staticvoid mainStringargs[J{ServerSocket server=null;Server_thread thread;Socket you=null;whiletrue二{try{server new ServerSocket4331;catchIOException e1正在监听对象不能重复创建{System.out.printin//ServerSocket等待客户呼叫;try{System.out.printing you=server.accept;客户的地址:System.out.println“+you.getInetAddress;catch TOExceptione正在等待客户;{System.out.printin ifyou!=null为每个客户启动一个专门的线程{new Server_threadyou.start;//class Server_thread extendsThread{Socket socket;DataOutputStream out=null;DatalnputStream in=null;String s=null;boolean quesion=false;Server_threadSocket t{socket=t;try{out=new DataOutputStreamsocket.getOutputStream;in=new DataInputStreamsocket.getlnputStream;catch lOExceptionepublic voidrun{whiletrue{double a[]=new double
[3];int i=0;〃堵塞状态,除非读取到信息try{s=in.readUTF;quesion=false;StringTokenizer fenxi=new StringTokenizers,H,n;whilefenxi.hasMoreTokens{String temp=fenxi.nextToken;try{a[iJ=Double.valueOftemp.doubleValue;i++;catchNumberFormatException e请输入数字字符{out.writeUTF quesion=true;ifquesion=false{double p=a
[0]+a[l]+a
[2]/
2.0;out.writeUTFn n4-Math.sqrtp*p-a
[0]*p-a[l]*p-a
[2];catch TOExceptione客户离开;{System.out.printlnreturn;••客户端2Client.javaimport java.net.*;import java.io.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;
二、选择题l.Ao
2.Co
3.Co
三、阅读程序你,苹,甜
1.好好
2.Jeep
3.x=-5,y=-l
四、编程序题
1.public class Xitil{public staticvoid mainStringargs[]{double sum=0,a=l;int i=l;whilei=20{sum=sum+a;i++;a=a*i;System.out.println,,sum=,,+sum;}
2.public classXiti2{public staticvoid mainStringargs[]{int ij;forj=2;j=100;j++{fori=2;i=j/2;i++{ifj%i=O break;ifij/2{System.out.print,n+j;
3.classXiti3{public staticvoid mainStringargs[]{double sum=0,a=do{sum=sum+a;i++;a=
1.0/i*a;}whilei=20;{public staticvoid mainStringargsf]{new ChatClient;class ChatClientextends Frameimplements Runnable,ActionListener{Button connection,send;TextField inputName,inputContent;TextArea chatResult;二Socket socketnull;DatalnputStream in=null;DataOutputStream out=null;Thread thread;String name=”;public ChatClient{socket=new Socket;Box boxl=Box.createHorizontalBox;connection=newButtonH连接服务器发送”;send=new Buttonsend.setEnabledfalse;inputName=new TextField6;inputContent=new TextField22;chatResult=new TextArea;box
1.addnewLabel,输入妮称:;box l.addinputName;box l.addconnection;Box box2=Box.createHorizontalBox;输入聊天内容:“;box
2.addnew Labelbox
2.addinputContent;box
2.addsend;connection.addActionListener this;send.addActionListener this;二thread new Threadthis;addbox1,BorderLayout.NORTH;addbox2,BorderLayout.SOUTH;addchatResult,BorderLayout.CENTER;setBoundsl0,30,400,280;setVisibletrue;validate;addWindowListenernew WindowAdapter{public voidwindowClosingWindowEvent e{System.exitO;};}public voidactionPerformedActionEvent e{ife.getSource==connection{try{ifsocket.isConnectedelse{InetAddress address=InetAddress.getByNamenl
27.
0.
0.ln;InetSocketAddress socketAddress=new InetSocketAddressaddress,666;socket.connectsocketAddress;in=new DatalnputStreamsocket.getInputStream;out=new DataOutputStreamsocket.getOutputStream;name=inputName.getText;姓名:out.writeUTF+name;send.setEnabledtrue;if!thread.isAlive二thread new Threadthis;thread.start;catch lOExceptionee{}ife.getSource==send{String s=inputContent.getText;ifs!=null聊天内容:”{try{out.writeUTF+name+”:+s;catchIOException el{}public voidrun{String s=null;whiletrue{try{s=in.readUTF;chatResult.append,\n,4-s;catchIOException e与服务器已断开{chatResult.setText try{socket.closeQ;catchException exp{}break;服务器端ChatServer.javaimport java.io.*;importjava.net.*;import java.util.*;public classChatServer{public staticvoid mainStringargs[]{ServerSocket server=null;Socket you=null;Hashtable peopleList;peopleList=new Hashtable;whiletrue{try{server=new ServerSocket666;catchIOException el正在监听;{System.out.printintry{you=server.accept;InetAddress address=you.getInetAddress;客户的System.out.printin IP:-address;catch lOExceptione{}ifyou!=null{Server_thread peopleThread=newServer_threadyou,peopleList;peopleThread.start;else{continue;classServer_thread extendsThread{String name=null;Socket socket=null;File file=null;DataOutputStream out=null;DatalnputStream in=null;Hashtable peopleList=null;Server_threadSocket t,Hashtable list{peopleList=list;socket=t;二try{in newDataInputStreamsocket.getInputStream;out=new DataOutputStreamsocket.getOutputStream;catch lOExceptione{}public voidrun{whiletrue{String s=null;trys=in.readUTF;姓名:ifs.starts With{name=s;boolean boo=peopleList.containsKeyname;ifboo==false{peopleList.putname,this;else请换妮称{out.writeUTFsocket.close;break;聊天内容”else ifs.startsWith{String message=s.substrings.indexOfn:n+1;Enumeration chatPersonList=peopleList.elements;whilechatPersonList.hasMoreElements聊天内容:“+{Server_threadchatPersonList.nextElement.out.writeUTFmessage;catchIOException ee{Enumeration chatPersonList=peopleList.elements;whilechatPersonList.hasMoreElements{try{Server_thread th=Server_threadchatPersonList.nextElement;ifth!=thisth.isAlive山.0a.\¥1>加1^17客户离线”+1101]1«;catchIOException eee{}}peopleList.removename;try{socket.close;catchIOException eee{}客户离开了System,out.printlnname+”break;
4.BroadCastWord.javaimport java.io.*;import java.net.*;import java.awt.*;import java.awt.event.*;import javax.swing.Timer;public classBroadCastWord extendsFrameimplementsActionListener{int port;二InetAddress groupnull;二MulticastSocket socketnull;Timer time=null;FileDialog open=null;开始广播,停止广播;Button select,File file=null;String FileDir=null,fileName=nun;FileReader in=null;BufferedReader bufferln=null;int token=0;显示正在播放内容,显示已播放的内容;TextAreapublic BroadCastWord单词广播系统{super选择要广播的文件select=new Button开始广播开始广播=new Button停止广播停止广播=new Buttonselect.addActionListenerthis;开始广^.addActionListenerthis;停止广播.add ActionListenerthis;time=new Timer2000,this;”选择要广播的文件”,open=new FileDiakgthis,FileDialog.LOAD;显示正在播放内容二ne w TextArea10,10;显示正在播放内§.setForegroundColor.blue;显示已播放的内容=new TextArea10,10;Panel north=new Panel;north.addselect;开始广播;north,add停止广播;north,addaddnorth,BorderLayout.NORTH;Panel center=new Panel;center.setLayoutnew GridLayoutl,2;显示正在播放内容;center,add显示已播放的内容;center,addaddcenter,BorderLayout.CENTER;validate;try{port=5000;group=InetAddress.getByNamen
239.
255..;socket=new MulticastSocketport;socket.setTimeToLive⑴;socket.joinGroupgroup;catchException e{System.out.printlnnError:+e;setBoundsl00,50,360,380;setVisibletrue;addWindowListenernew WindowAdapter{public voidwindowClosingWindowEvent e{System.exitO;};public voidactionPerformedActionEvent e{ife.getSource==select{显示已播放的内容.setTextnull;open.setVisibletrue;fileName=open.getFile;FileDir=open.getDirectory;iffileName!=null{time.stopO;file=new FileFileDir,fileName;try{file=new FileFileDir,fileName;二in new FileReaderfile;二bufferin newBufferedReaderin;catchIOException ee{}开始广播else ife.getSource=={time.start;else ife.getSource=time{String s=null;try{iftoken=-l{file=new FileFileDir,fileName;in=newFileReaderfile;bufferln=new BufferedReaderin;s=bufferIn.readLine;ifs!=null{token=0;显示正在播放内容正在广播的内容:.setText\n+s;显示已播放的内容.appends+”\n;DatagramPacket packet=null;byte data[]=s.getBytes;packet=new DatagramPacketdata,data.length,group,port;socket.sendpacket;else{token-1;catchIOException ee{}停止广播else ife.getSource=={time.stopO;}public staticvoid mainString[J args二{BroadCastWord broadnew BroadCastWord;Receive.javaimportjava.net.*;import java.awt.5^;import java.awt.event.*;public classReceive extendsFrameimplementsRunnable,ActionListener{int port;InetAddress group=null;二MulticastSocket socketnull;开始接收,停止接收;Button显示正在接收内容,显示已接收的内容;TextAreaThread thread;停止boolean=false;public Receive”定时接收信息{superthread=newThreadthis;开始接收开始接收=new Button停止接收停止接收=new Button停止接收.add ActionListenerthis;开始接收.add ActionListenerthis;显示正在接收内容=澳w TextArea10,10;显示正在接收内§.setForegroundColor.blue;显示已接收的内容=慎wTextArea10,10;Panel north=new Panel;开始接收;north,add停止接收;north,addaddnorth,BorderLayout.NORTH;二Panel centernew Panel;center.setLayoutnew GridLayoutl,2;显示正在接收内容;center,add显示已接收的内容;center,addaddcenter,BorderLayout.CENTER;validate;port=5000;try{group=InetAddress.getByNamen
239.
255.
0.0*;socket=new MulticastSocketport;socket.joinGroupgroup;catchException e{}setBounds100,50,360,380;setVisibletrue;addWindowListenernew WindowAdapter{public voidwindowClosingWindowEvent e{System.exitO;};public voidactionPerformedActionEvent e开始接收{ife.getSource=={开始接收.setBackgroundColor.blue;停止接收.setBackgroundColor.gray;if!thread.isAlive{thread=newThreadthis;try{thread.start;停止=false;catchException ee{}停止接收ife.getSource=={开始接收.setBackgroundColor.gray;停止接收.setBackgroundColor.blue;thread.interrupt;停止二true;public voidrun{whiletrue{byte dataLJ=new byte[8192J;DatagramPacket packet=null;packet=newDatagramPacketdata,data.length,group,port;try{socket.receivepacket;String message=new Stringpacket.getData,O,packet.getLength;显示正在接收内容正在接收的内容:.setText\n”+message;显示已接收的内容.appendmessage+“\n”;停止catchException e{}if==true{break;public staticvoid mainStringargs[J{new Receive;}习题第章1414
一、问答题个参数L2个参数
2.6个参数
3.7创建对象,进行旋转操作,绘制旋转的图形
4.1AffineTransform23使用循环计算的System.out.println do-while sum=+sum;forsum=0,i=l,a=l;iv=20;i++{a=a*
1.0/i;sum=sum+a;使用循环计算的System.out.println forsum=+sum;
4.public classXiti4{public staticvoid mainStringargs[]{int sum=0,i,j;fori=l;i=1000;i++{forj=l,sum=0;ji;j++{ifi%j=Osum=sum+j;ifsum=i完数:“System,out.printin+i;
5.public classXiti5{public staticvoid mainStringargs[]{int m=8,item=m,i=l;long sum=0;fori=1,sum=O,item=m;i=10;i++{sum=sum+item;item=item*10+m;}System.out.printlnsum;
6.public classXiti6{public staticvoid mainStringargs[]{int n=l;long sum=;whiletrue{sum=sum+n;n++;ifsum=8888break;满足条件的最大整数:System,out.println+n-l;、编写程序
1.impor.java.awt.*;import javax.swing.*;class MyCanvasextends Canvas{static intpointX[]=new int
[5],pointYf]=new int
[5];public voidpaintGraphics g{〃进行坐标变换,将新的坐标原点设置为g.translate200,200;200,200pointX
[0]=0;pointY
[0]=-120;double arcAngle=72*Math.PI/l80;forint i=l;i5;i++{pointX[i]=intpointX[i-l]*Math.cosarcAngle-pointY[i-l]*Math.sinarcAngle;pointY[i]=intpointY[i-1]*Math.cosarcAngle+pointX[i-1]*Math.sinarcAngle;g.setColorColor.red;int starX[]={pointX
[0],pointX
[2],pointX
[4],pointX
[1],pointX
[3],pointX
[0]};int starY[]={pointY
[0],pointY
[2],pointY
[4],pointY
[1],pointY
[3],pointY
[0]};g.drawPolygonstarX,starY,6;public classE{public staticvoid mainStringargsLJ{JFrame f=new JFrame;f.setSize500,450;f.setVisibletrue;MyCanvas canvas=new MyCanvas;f.addcanvas,HCentern;f.validate;f.setDefaultCloseOperationJFrame.DISPOSE_ON_CLOSE;}
2.・impor.java・awt・*;import javax.swing.*;import java.awt.geom.*;class MyCanvasextends Canvas{public voidpaintGraphics g{g.setColorColor.red;Graphics2D g_2d=Graphics2Dg;QuadCurve2D quadCurve=new QuadCurve2D.Double2,10,51,90,100,10;g_2d.drawquadCurve;quadCurve.setCurve2,100,51,10,100,100;g_2d.drawquadCurve;public classE{public staticvoid mainStringargs[]{JFrame f=new JFrame;f.setSize500,450;f.setVisibletrue;MyCanvas canvas=new MyCanvas;f.addcanvas,Center;f.validate;f.setDefaultCloseOperationJFrame.DISPOSE_ON_CLOSE;3・・impor.java.awt.*;import javax.swing.*;import java.awt.geom.*;class MyCanvasextends Canvas{public voidpaintGraphics g{g.setColorColor.red;Graphics2D g_2d=Graphics2Dg;CubicCurve2D cubicCurve=new CubicCurve2D.Double0,70,70,140,140,0,210,70;g_2d.drawcubicCurve;public classE{public staticvoid mainStringargs[]{JFrame f=new JFrame;f.setSize500,450;f.setVisibletrue;MyCanvas canvas=new MyCanvas;f.addcanvas,Center1;f.validate;f.setDefaultCloseOperationJFrame.DISPOSE_ON_CLOSE;4・・impor.java.awt.*;import javax.swing.*;import java.awt.geom.*;class Flowerextends Canvas{public voidpaintGraphics g{Graphics2D g_2d=Graphics2Dg;〃花叶两边的曲线QuadCurve2D二curve_1new QuadCurve2D.Double200,200,150,160,200,100;CubicCurve2D curve_2=new CubicCurve2D.Double200,200,260,145,190J20,200,100;〃花叶中的纹线Line2D line=new Line2D.Double200,200,200,110;QuadCurve2D leaf_linel=new QuadCurve2D.Double200,180,195,175,190,170;QuadCurve2D Ieaf_line2=new QuadCurve2D.Double200,180,210,175,220,170;QuadCurve2D leaf_line3=new QuadCurve2D.Double200,160,195,155,190,150;QuadCurve2D leaf_line4=new QuadCurve2D.Double200,160,214,155,220,150;〃利用旋转来绘制花朵AffineTransform trans=new AffineTransform;forint i=0;i6;i++{trans.rotate60*Math.PI/180,200,200;g_2d.setTransformtrans;GradientPaint gradient_l=new GradientPaint200,200,Color.green,200,100,Color.yellow;g_2d.setPaintgradient_l;g_2d.fillcurve_l;GradientPaint gradient_2=newGradientPaint200,l45,Color.green,260,145,Color.red,true;g_2d.setPaintgradient_2;g_2d.fillcurve_2;Color c3=new Color0,200,0;g_2d.setColorc3;g_2d.drawline;g_2d.drawleaCHne1;g_2d.draw1eaf^line2;g_2d.drawleafLHne3;g_2d.drawleaf_line4;〃花瓣中间的花蕾曲线QuadCurve2D center_curve_l=new QuadCurve2D.Double200,200,190,185,200,180;AffineTransform trans_l=new AffineTransform;forint i=0;i12;i++{trans_l.rotate30*Math.PI/l80,200,200;g_2d.setT ransformtrans_1;GradientPaint gradient_3=new GradientPaint200,200,Color.red,200,180,Color.yellow;g_2d.setPaintgradient_3;g_2d.fillcenter_curve_l;public classE{public staticvoid mainStringargs[]{JFrame f=new JFrame;f.setSize500,450;f.setVisibletrue;二Flower canvasnew Flower;f.addcanvas,nCentern;f.validate;f.setDefaultCloseOperationJFrame.DISPOSE_ON_CLOSE;
5.import java.awt.*;import javax.swing.*;import java.awt.geom.*;class Moonextends Canvas{public voidpaintGraphics g{Graphics2D g_2d=Graphics2Dg;Ellipse2D ellipse1=...ne.Ellipse2D.Doubl.20,80,60,60,ellipse2=...ne.Ellipse2D.Doubl.40,80,80,80;g_2d.setColorColor.white;Area al=new Areaellipsel,a2=new Areaellipse2;〃“差”al.subtracta2;public classE{public staticvoid mainStringargs[]{JFrame f=new JFrame;f.setSize500,450;f.setVisibletrue;Moon moon=new Moon;moon.setBackgroundColor.black;f.addmoon,Center0;f.validate;f.setDefaultCloseOperationJFrame.DISPOSE_ON_CLOSE;习题第章1515
一、问答题使用链式存储结构,使用顺序存储结构
1.LinkedList ArrayList迭代器遍历在找到集合中的一个对象的同时,也得到待遍历的后继对象的引用,因此迭
2.代器可以快速地遍历集合不是
3.用>来存储
4.HashMapvK,V
二、阅读程序
1.8-
2.ABCDo
三、编写程序
1.impor.java.util.*;public classE{public staticvoid mainStringargs[]{StackInteger stack=new StackInteger;stack.pushnew Integer3;stack.pushnew Integer8;int k=l;whilek=10{forint i=l;i=2;i++{Integer Fl=stack.pop;int fl=Fl.intValue;Integer F2=stack.pop;int f2=F
2.intValue;Integer temp=new Integer2*f1+2*f2;System.out.printlnn,4-temp.toString;stack.pushtemp;stack.pushF2;k++;
2..impor.java.utiL^;class Studentimplements Comparable{int english=0;String name;Studentint english,String name{this.name=name;this.english=english;public intcompareToObject b{二Student stStudentb;return this.english-st.english;public classE{public staticvoid mainStringargs[J{ListStudent list=new LinkedListStudent;int score[]={65,76,45,99,77,88,100,79;口二{“张三”李四「旺季加戈“为哈”周和久赵李将集”};String nameJ JJ Jforinti=0;iscore.length;i++{list.addnew Studentscore[i],name[i];IteratorStudent iter=list.iterator;TreeSetStudent mytree=new TreeSetStudent;whileiter.hasNext{Student stu=iter.next;mytree.addstu;IteratorStudent te=mytree.iterator;whilete.hasNext{Student stu=te.next;System.out.printlnnn+stu.name+n n4-stu.english;
3.impor.java.util.*;class UDiscKeyimplements Comparable{double key=0;UDiscKeydouble d{key=d;public intcompareToObject b{UDiscKey disc=UDiscKeyb;ifthis.key-disc.key==0return-1;elsereturn intthis.key-disc.key*1000;class UDisc{int amount;double price;UDiscint m,double e{amount=m;price=e;public classE{public staticvoid mainStringargs[]{TreeMapUDiscKey,UDisc treemap=new TreeMapUDiscKey,UDisc;intamount[]={1,2,4,8,16};double price[]={867,266,390,556};UDisc UDisc[]=new UDisc
[4];forint k=O;kUDisc.length;k++{UDisc[k]=new UDiscamount[k],price[k];UDiscKey key[]=new UDiscKey
[4];forint k=O;kkey.length;k++{key[k]=new UDiscKeyUDisc[k].amount;forint k=O;kUDisc.length;k++{treemap.putkey[k],UDi sc[k];int number=treemap.size;CollectionUDisc collection=treemap.values;IteratorUDisc iter=collection.iterator;whileiter.hasNext{UDisc disc=iter.next;System.out.println,M,4-disc.amount4-nG+disc.price+“元;treemap.clear;forint k=O;kkey.length;k++{key[k]=new UDiscKeyUDisc[k].price;〈forint k=O;k UDisc.length;k++{treemap.putkey[k],UDisc[k];number=treemap.size;;collection=treemap.valuesiter=collection.iterator;whileiter.hasNext{UDisc disc=iter.next;System.out.printlnn,,+disc.amount4-,G+disc.price+“元;习题(第章)44
一、问答题封装、继承和多态L当类名由几个单词复合而成时,每个单词的首字母使用大写
2.名字的首单词的首字母使用小写,如果变量的名字由多个单词组成,从第个单词开始的其它单
3.2词的首字母使用大写属性
4..行为5用类创建对象时没有类型
6.用类创建对象时
7.一个类中可以有多个方法具有相同的名字,但这些方法的参数必须不同,即或者是参数的个数不
8.同,或者是参数的类型不同可以可以不可以
9.不可以
10.一个类通过使用运算符可以创建多个不同的对象,不同的对象的实例变量将被分配不同的
11.new内存空间所有对象的类变量都分配给相同的一处内存,对象共享类变量代表调用当前方法的对象不可以
12.
二、选择题【代码】【代码】【代码】
1.Bo
2.Do
3.Do
4.Do
5.CD
6.
147.4
三、阅读程序【代码】【代码】:【代码】:
1.11,2121,312E
2.sum=-100o
3.27o【代码】【代码】:
4.1:100,
220.Oo.上机实习题目,解答略
5.上机实习题目,解答略6
四、编程题CPU.javapublic classCPU{int speed;int getSpeed{return speed;public voidsetSpeedint speed{this.speed=speed;HardDisk.javapublic classHardDisk{int amount;int getAmount{return amount;public voidsetAmountint amount{this.amount=amount;PC.javapublic classPC{CPU cpu;HardDisk HD;二void setCPUCPU cpu{this.cpu cpu;void setHardDiskHardDisk HD{this.HD=HD;void show{System.out.printlnHCPU速度:+cpu.getSpeed;硬盘容量:“System,out.printin+HD.getAmount;Test.javapublic classTest{public staticvoid mainStringargs[J{CPUcpu=new CPU;HardDiskHD=new HardDisk;cpu.setSpeed2200;HD.setAmount200;PC pc=new PC;pc.setCPUcpu;pc.setHardDiskHD;pc.show;习题第章55
一、问答题
1.不可以
2.是
3.不继承
4.声明与父类同名的成员变量
5.子类重写的方法类型和父类的方法的类型一致或者是父类的方法的类型的子类型,重写的方法的名字、参数个数、参数的类型和父类的方法完全相同重写方法的目的是隐藏继承的方法,子类通过方法的重写可以把父类的状态和行为改变为自身的状态和行为
6.不可以
7.abstract类
8.上转型对象不能操作子类新增的成员变量,不能调用子类新增的方法上转型对象可以访问子类继承或隐藏的成员变量,可以调用子类继承的方法或子类重写的实例方法
9.通过重写方法
10.面向抽象编程目的是为了应对用户需求的变化,核心是让类中每种可能的变化对应地交给抽象类的一个子类类去负责,从而让该类的设计者不去关心具体实现
二、选择题
1.Co
2.Do
3.CDo
4.Do
5.Bo
6.Bo
7.Do
8.Bo
9.Ao
三、阅读程序[代码[代码]
1.11:
15.02:
8.0o
2.【代码1】11【代码2】H【代码】【代码】【代码】【代码】
3.
198.0212o
398.049【代码】【代码】【代码】
4.112021203-100
四、编程题Animal,javapublic abstractclass Animal{public abstractvoid cry;public abstractString getAnimalName;Simulator,javapublic classSimulator{public voidplaySoundAnimal animal{现在播放类的声音:;System.out.print+animaLgetAnimalName+”animal.cryO;Dog.javapublic classDog extendsAnimal{public void cry{汪汪..•汪汪”;System.out.println}狗”;public String getAnimalName{returnCat.javapublic classCat extendsAnimal{public voidcry{瞄口苗…口苗口苗”;Sy stem.out.println猫”;public StringgetAnimalName{return}Application,javapublic classExample5_13{public staticvoid mainStringargs[]{Simulator simulator=new Simulator;simulator.playSoundnew Dog;simulator.playSoundnew Cat;}习题(第章)66
一、问答题
1.不能
2.不能
3.可以把实现某一接口的类创建的对象的引用赋给该接口声明的接口变量中那么该接口变量就可以调用被类实现的接口中的方法
4.不可以
5.可以
二、选择题
1.Do
2.ABo
3.Bo
三、阅读程序[代码[代码
1.1]:
15.02]:8o【代码】【代码】
2.118215o
四、编程题Animal,javapublic interfaceAnimal{public abstractvoidcry;public abstractStringgetAnimalName;Simulator,javapublic classSimulator{public voidplaySoundAnimal animal{现在播放类的声音:;System,out.print+animaLgetAnimalName+”animaLcryO;}Dog.javapublic classDog implementsAnimal{public voidcry{汪汪…汪汪System.out.printin狗”;public StringgetAnimalName{returnCat.javapublic classCat implementsAnimal{public voidcry{嗜嘀…口苗唯”;System.out.printlnpublic StringgetAnimalName{猫”;returnApplication,java。