java2实用教程第4版-习题解答

上传人:gbs****77 文档编号:9808112 上传时间:2020-04-08 格式:DOC 页数:51 大小:268.50KB
返回 下载 相关 举报
java2实用教程第4版-习题解答_第1页
第1页 / 共51页
java2实用教程第4版-习题解答_第2页
第2页 / 共51页
java2实用教程第4版-习题解答_第3页
第3页 / 共51页
点击查看更多>>
资源描述
习题解答 习题一 第 1 章 一 问答题 1 James Gosling 2 需 3 个步骤 1 用文本编辑器编写源文件 2 使用 javac 编译源文件 得到字节码文件 3 使用解释器运行程序 3 由类所构成 应用程序必须有一个类含有 public static void main String args 方法 含 有该方法的类称为应用程序的主类 不一定 但最多有一个 public 类 4 set classpath D jdk jre lib rt jar 5 java 和 class 6 java Bird 7 独行风格 大括号独占行 和行尾风格 左大扩号在上一行行尾 右大括号独占行 二 选择题 1 B 2 D 三 阅读程序 1 a Person java b 两个字节码 分别是 Person class 和 Xiti class c 得到 NoSuchMethodError 得到 NoClassDefFoundError Xiti class 得到 您好 很高兴 认识您 nice to meet you 习题二 第 2 章 一 问答题 1 用来标识类名 变量名 方法名 类型名 数组名 文件名的有效字符序列称为标识 符 标识符由字母 下划线 美元符号和数字组成 第一个字符不能是数字 false 不是 标识符 2 关键字就是 Java 语言中已经被赋予特定意义的一些单词 不可以把关键字作为名字来 用 不是关键字 class implements interface enum extends abstract 3 boolean char byte short int long float double 4 float 常量必须用 F 或 f 为后缀 double 常量用 D 或 d 为后缀 但允许省略后缀 5 一维数组名 length 二维数组名 length 二 选择题 1 C 2 ADF 3 B 4 BE 5 代码 2 代码 3 代码 4 代码 5 6 B 三 阅读或调试程序 1 属于操作题 解答略 2 属于操作题 解答略 3 属于操作题 解答略 4 代码 1 4 代码 2 b 0 1 5 代码 1 40 代码 2 7 四 编写程序 1 public class E public static void main String args System out println int 你 System out println int 我 System out println int 他 2 public class E public static void main String args char cStart cEnd for char c cStart c cEnd c System out print c 习题三 第 3 章 一 问答题 1 boolean 2 不可以 3 boolean 4 不是必须的 5 结束 while 语句的执行 6 可以 二 选择题 1 A 2 C 3 C 三 阅读程序 1 你 苹 甜 2 Jeep 好好 3 x 5 y 1 四 编程序题 1 public class Xiti1 public static void main String args double sum 0 a 1 int i 1 while i 10 sum sum a i a a i System out println sum sum 2 public class Xiti2 public static void main String args int i j for j 2 j 100 j for i 2 ij 2 System out print j 3 class Xiti3 public static void main String args double sum 0 a 1 i 1 do sum sum a i a 1 0 i a while i 20 System out println 使用 do while 循环计算的 sum sum for sum 0 i 1 a 1 i 20 i a a 1 0 i sum sum a System out println 使用 for 循环计算的 sum sum 4 public class Xiti4 public static void main String args int sum 0 i j for i 1 i 1000 i for j 1 sum 0 j i j if i j 0 sum sum j if sum i System out println 完数 i 5 public class Xiti5 public static void main String args int m 8 item m i 1 long sum 0 for i 1 sum 0 item m i 8888 break System out println 满足条件的最大整数 n 1 习题四 第 4 章 一 问答题 1 封装 继承和多态 2 当类名由几个单词复合而成时 每个单词的首字母使用大写 3 名字的首单词的首字母使用小写 如果变量的名字由多个单词组成 从第 2 个单词开 始的其它单词的首字母使用大写 4 属性 5 行为 6 用类创建对象时 没有类型 7 用类创建对象时 8 一个类中可以有多个方法具有相同的名字 但这些方法的参数必须不同 即或者是参 数的个数不同 或者是参数的类型不同 可以 9 可以 不可以 10 不可以 11 一个类通过使用 new 运算符可以创建多个不同的对象 不同的对象的实例变量将被 分配不同的内存空间 所有对象的类变量都分配给相同的一处内存 对象共享类变量 12 代表调用当前方法的对象 不可以 二 选择题 1 B 2 D 3 D 4 D 5 CD 6 代码 1 代码 4 7 代码 4 三 阅读程序 1 代码 1 1 代码 2 121 代码 3 121 2 sum 100 3 27 4 代码 1 100 代码 2 20 0 5 上机实习题目 解答略 6 上机实习题目 解答略 四 编程题 CPU java public class CPU int speed int getSpeed return speed public void setSpeed int speed this speed speed HardDisk java public class HardDisk int amount int getAmount return amount public void setAmount int amount this amount amount PC java public class PC CPU cpu HardDisk HD void setCPU CPU cpu this cpu cpu void setHardDisk HardDisk HD this HD HD void show System out println CPU 速度 cpu getSpeed System out println 硬盘容量 HD getAmount Test java public class Test public static void main String args CPU cpu new CPU HardDisk HD new HardDisk cpu setSpeed 2200 HD setAmount 200 PC pc new PC pc setCPU cpu pc setHardDisk HD pc show 习题五 第 5 章 一 问答题 1 不可以 2 是 3 不继承 4 声明与父类同名的成员变量 5 子类重写的方法类型和父类的方法的类型一致或者是父类的方法的类型的子类型 重 写的方法的名字 参数个数 参数的类型和父类的方法完全相同 重写方法的目的是隐 藏继承的方法 子类通过方法的重写可以把父类的状态和行为改变为自身的状态和行为 6 不可以 7 Abstract 类 8 上转型对象不能操作子类新增的成员变量 不能调用子类新增的方法 上转型对象可 以访问子类继承或隐藏的成员变量 可以调用子类继承的方法或子类重写的实例方法 9 通过重写方法 10 面向抽象编程目的是为了应对用户需求的变化 核心是让类中每种可能的变化对应 地交给抽象类的一个子类类去负责 从而让该类的设计者不去关心具体实现 二 选择题 1 C 2 D 3 CD 4 D 5 B 6 B 7 D 8 B 9 A 三 阅读程序 1 代码 1 15 0 代码 2 8 0 2 代码 1 11 代码 2 11 3 代码 1 98 0 代码 2 12 代码 3 98 0 代码 4 9 4 代码 1 120 代码 2 120 代码 3 100 四 编程题 Animal java public abstract class Animal public abstract void cry public abstract String getAnimalName Simulator java public class Simulator public void playSound Animal animal System out print 现在播放 animal getAnimalName 类的声音 animal cry Dog java public class Dog extends Animal public void cry System out println 汪汪 汪汪 public String getAnimalName return 狗 Cat java public class Cat extends Animal public void cry System out println 喵喵 喵喵 public String getAnimalName return 猫 Application java public class Example5 13 public static void main String args Simulator simulator new Simulator simulator playSound new Dog simulator playSound new Cat 习题六 第 6 章 一 问答题 1 不能 2 不能 3 可以把实现某一接口的类创建的对象的引用赋给该接口声明的接口变量中 那么该接 口变量就可以调用被类实现的接口中的方法 4 不可以 5 可以 二 选择题 1 D 2 AB 3 B 三 阅读程序 1 代码 1 15 0 代码 2 8 2 代码 1 18 代码 2 15 四 编程题 Animal java public interface Animal public abstract void cry public abstract String getAnimalName Simulator java public class Simulator public void playSound Animal animal System out print 现在播放 animal getAnimalName 类的声音 animal cry Dog java public class Dog implements Animal public void cry System out println 汪汪 汪汪 public String getAnimalName return 狗 Cat java public class Cat implements Animal public void cry System out println 喵喵 喵喵 public String getAnimalName return 猫 Application java public class Example5 13 public static void main String args Simulator simulator new Simulator simulator playSound new Dog simulator playSound new Cat 习题七 第 7 章 一 问答题 1 有效 2 可以 3 不可以 4 一定是 二 选择题 1 C 2 C 三 阅读程序 1 大家好 祝工作顺利 2 p 是接口变量 3 你好 fine thanks 4 属于上机实习程序 解答略 四 编程题 import java util public class E public static void main String args Scanner reader new Scanner System in double sum 0 int m 0 while reader hasNextDouble double x reader nextDouble assert x 100 数据不合理 m m 1 sum sum x System out printf d 个数的和为 f n m sum System out printf d 个数的平均值是 f n m sum m 习题八 第 8 章 一 问答题 1 不是 hello 是 2 4 和 3 3 false 和 true 4 负数 5 是 true 6 3 和 1 7 会发生 NumberFormatException 异常 二 选择题 1 A 2 C 3 B 4 D 5 C 三 阅读程序 1 代码 苹果 2 代码 Love Game 3 代码 1 15 代码 2 abc 我们 4 代码 13579 5 代码 9javaHello 6 属于上机实习程序 解答略 7 属于上机实习程序 解答略 四 编程题 1 public class E public static void main String args String s1 s2 t1 ABCDabcd s1 t1 toUpperCase s2 t1 toLowerCase System out println s1 System out println s2 String s3 s1 concat s2 System out println s3 2 public class E public static void main String args String s ABCDabcd char cStart s charAt 0 char cEnd s charAt s length 1 System out println cStart System out println cEnd 3 import java util public class E public static void main String args int year1 month1 day1 year2 month2 day2 try year1 Integer parseInt args 0 month1 Integer parseInt args 1 day1 Integer parseInt args 2 year2 Integer parseInt args 3 month2 Integer parseInt args 4 day2 Integer parseInt args 5 catch NumberFormatException e year1 2012 month1 0 day1 1 year2 2018 month2 0 day2 1 Calendar calendar Calendar getInstance calendar set year1 month1 1 day1 long timeYear1 calendar getTimeInMillis calendar set year2 month2 1 day2 long timeYear2 calendar getTimeInMillis long 相隔天数 Math abs timeYear1 timeYear2 1000 60 60 24 System out println year1 年 month1 月 day1 日和 year2 年 month2 月 day2 日相隔 相隔天数 天 4 import java util public class E public static void main String args double a 0 b 0 c 0 a 12 b 24 c Math asin 0 56 System out println c c Math cos 3 14 System out println c c Math exp 1 System out println c c Math log 8 System out println c 5 public class E public static void main String args String str ab123you 你是谁 String regex D str str replaceAll regex System out println str 6 import java util public class E public static void main String args String cost 数学 87 分 物理 76 分 英语 96 分 Scanner scanner new Scanner cost scanner useDelimiter 0123456789 double sum 0 int count 0 while scanner hasNext try double score scanner nextDouble count sum sum score System out println score catch InputMismatchException exp String t scanner next System out println 总分 sum 分 System out println 平均分 sum count 分 习题九 第 9 章 一 问答题 1 Frame 容器的默认布局是 BorderLayout 布局 2 不可以 3 ActionEvent 4 DocumentEvent 5 5 个 6 MouseMotionListener 二 选择题 1 C 2 A 3 A 4 D 5 C 三 编程题 1 import java awt import javax swing event import javax swing import java awt event public class E public static void main String args Computer fr new Computer class Computer extends JFrame implements DocumentListener JTextArea text1 text2 int count 1 double sum 0 aver 0 Computer setLayout new FlowLayout text1 new JTextArea 6 20 text2 new JTextArea 6 20 add new JScrollPane text1 add new JScrollPane text2 text2 setEditable false text1 getDocument addDocumentListener this setSize 300 320 setVisible true validate setDefaultCloseOperation JFrame DISPOSE ON CLOSE public void changedUpdate DocumentEvent e String s text1 getText String a s split 0123456789 sum 0 aver 0 for int i 0 i 0 m m 1 random seek m int c random readByte if c 0 System out print char c else m m 1 random seek m byte cc new byte 2 random readFully cc System out print new String cc catch Exception exp 2 import java io public class E public static void main String args File file new File E java File tempFile new File temp txt try FileReader inOne new FileReader file BufferedReader inTwo new BufferedReader inOne FileWriter tofile new FileWriter tempFile BufferedWriter out new BufferedWriter tofile String s null int i 0 s inTwo readLine while s null i out write i s out newLine s inTwo readLine inOne close inTwo close out flush out close tofile close catch IOException e 3 import java io import java util public class E public static void main String args File file new File a txt Scanner sc null double sum 0 int count 0 try sc new Scanner file sc useDelimiter 0123456789 while sc hasNext try double price sc nextDouble count sum sum price System out println price catch InputMismatchException exp String t sc next System out println 平均价格 sum count catch Exception exp System out println exp 习题十一 第 11 章 一 问答题 1 1 添加数据源 2 选择驱动程序 3 命名数据源名称 2 不必使用数据名称 3 减轻数据库内部 SQL 语句解释器的负担 4 事务由一组 SQL 语句组成 所谓事务处理是指 应用程序保证事务中的 SQL 语句要 么全部都执行 要么一个都不执行 5 1 用 setAutoCommit 方法关闭自动提交模式 2 用 commit 方法处理事务 3 用 rollback 方法处理事务失败 四 编程题 1 import java sql import java util public class E public static void main String args Query query new Query String dataSource myData String tableName goods Scanner read new Scanner System in System out print 输入数据源名 dataSource read nextLine System out print 输入表名 tableName read nextLine query setDatasourceName dataSource query setTableName tableName query setSQL SELECT FROM tableName query inputQueryResult class Query String datasourceName 数据源名 String tableName 表名 String SQL SQL 语句 public Query try Class forName sun jdbc odbc JdbcOdbcDriver catch ClassNotFoundException e System out print e public void setDatasourceName String s datasourceName s trim public void setTableName String s tableName s trim public void setSQL String SQL this SQL SQL trim public void inputQueryResult Connection con Statement sql ResultSet rs try String uri jdbc odbc datasourceName String id String password con DriverManager getConnection uri id password DatabaseMetaData metadata con getMetaData ResultSet rs1 metadata getColumns null null tableName null int 字段个数 0 while rs1 next 字段个数 sql con createStatement rs sql executeQuery SQL while rs next for int k 1 k 字段个数 k System out print rs getString k System out println con close catch SQLException e System out println 请输入正确的表名 e 2 import java sql import java util public class E public static void main String args Query query new Query String dataSource myData String tableName goods query setDatasourceName dataSource query setTableName tableName String name Scanner read new Scanner System in System out print 商品名 name read nextLine String str name String SQL SELECT FROM tableName WHERE name LIKE str query setSQL SQL System out println tableName 表中商品名是 name 的记录 query inputQueryResult class Query String datasourceName 数据源名 String tableName 表名 String SQL SQL 语句 public Query try Class forName sun jdbc odbc JdbcOdbcDriver catch ClassNotFoundException e System out print e public void setDatasourceName String s datasourceName s trim public void setTableName String s tableName s trim public void setSQL String SQL this SQL SQL trim public void inputQueryResult Connection con Statement sql ResultSet rs try String uri jdbc odbc datasourceName String id String password con DriverManager getConnection uri id password DatabaseMetaData metadata con getMetaData ResultSet rs1 metadata getColumns null null tableName null int 字段个数 0 while rs1 next 字段个数 sql con createStatement rs sql executeQuery SQL while rs next for int k 1 k 字段个数 k System out print rs getString k System out println con close catch SQLException e System out println 请输入正确的表名 e 3 将例子 5 中的代码 String SQL SELECT FROM tableName ORDER BY name 更改为 String SQL SELECT FROM tableName ORDER BY madeTime 可达题目要求 习题十二 第 12 章 一 问答题 1 4 种状态 新建 运行 中断和死亡 2 有 4 种原因的中断 1 JVM 将 CPU 资源从当前线程切换给其他线程 使本线程让 出 CPU 的使用权处于中断状态 2 线程使用 CPU 资源期间 执行了 sleep int millsecond 方法 使当前线程进入休眠状态 3 线程使用 CPU 资源期间 执行了 wait 方法 使得当前线程进入等待状态 4 线程使用 CPU 资源期间 执行某个操作进入阻 塞状态 比如执行读 写操作引起阻塞 3 死亡状态 不能再调用 start 方法 4 新建和死亡状态 5 两种方法 用 Thread 类或其子类 6 使用 setPrority int grade 方法 7 Java 使我们可以创建多个线程 在处理多线程问题时 我们必须注意这样一个问题 当两个或多个线程同时访问同一个变量 并且一个线程需要修改这个变量 我们应对这 样的问题作出处理 否则可能发生混乱 8 当一个线程使用的同步方法中用到某个变量 而此变量又需要其它线程修改后才能符 合本线程的需要 那么可以在同步方法中使用 wait 方法 使用 wait 方法可以中断方法的 执行 使本线程等待 暂时让出 CPU 的使用权 并允许其它线程使用这个同步方法 其 它线程如果在使用这个同步方法时不需要等待 那么它使用完这个同步方法的同时 应 当用 notifyAll 方法通知所有的由于使用这个同步方法而处于等待的线程结束等待 9 不合理 10 吵醒 休眠的线程 一个占有 CPU 资源的线程可以让休眠的线程调用 interrupt 方 法 吵醒 自己 即导致休眠的线程发生 InterruptedException 异常 从而结束休眠 重 新排队等待 CPU 资源 二 选择题 1 A 2 A 3 B 三 阅读程序 1 属于上机调试题目 解答略 2 属于上机调试题目 解答略 3 属于上机调试题目 解答略 4 属于上机调试题目 解答略 5 属于上机调试题目 解答略 6 属于上机调试题目 解答略 7 代码 BA 8 属于上机调试题目 解答略 四 编写程序 1 public class E public static void main String args Cinema a new Cinema a zhang start a sun start a zhao start class TicketSeller 负责卖票的类 int fiveNumber 3 tenNumber 0 twentyNumber 0 public synchronized void sellTicket int receiveMoney if receiveMoney 5 fiveNumber fiveNumber 1 System out println Thread currentThread getName 给我 5 元钱 这是您的 1 张入场卷 else if receiveMoney 10 while fiveNumber 1 try System out println Thread currentThread getName 靠边等 wait System out println Thread currentThread getName 结束等待 catch InterruptedException e fiveNumber fiveNumber 1 tenNumber tenNumber 1 System out println Thread currentThread getName 给我 10 元钱 找您 5 元 这是您的 1 张入场卷 else if receiveMoney 20 while fiveNumber 1 tenNumber 1 try System out println Thread currentThread getName 靠边等 wait System out println Thread currentThread getName 结束等待 catch InterruptedException e fiveNumber fiveNumber 1 tenNumber tenNumber 1 twentyNumber twentyNumber 1 System out println Thread currentThread getName 给 20 元钱 找您一张 5 元和一张 10 元 这是您的 1 张入场卷 notifyAll class Cinema implements Runnable Thread zhang sun zhao TicketSeller seller Cinema zhang new Thread this sun new Thread this zhao new Thread this zhang setName 张小有 sun setName 孙大名 zhao setName 赵中堂 seller new TicketSeller public void run if Thread currentThread zhang seller sellTicket 20 else if Thread currentThread sun seller sellTicket 10 else if Thread currentThread zhao seller sellTicket 5 2 参照本章例子 6 3 参照本章例子 9 习题十三 第 13 章 一 问答题 1 一个 URL 对象通常包含最基本的三部分信息 协议 地址 资源 2 URL 对象调用 InputStream openStream 方法可以返回一个输入流 该输入流指向 URL 对象所包含的资源 通过该输入流可以将服务器上的资源信息读入到客户端 3 客户端的套接字和服务器端的套接字通过输入 输出流互相连接后进行通信 4 使用方法 accept accept 会返回一个和客户端 Socket 对象相连接的 Socket 对象 accept 方法会堵塞线程的继续执行 直到接收到客户的呼叫 5 域名 IP 四 编程题 1 1 客户端 import import java io import java awt import java awt event import javax swing public class Client public static void main String args new ComputerClient class ComputerClient extends Frame implements Runnable ActionListener Button connection send TextField inputText showResult Socket socket null DataInputStream in null DataOutputStream out null Thread thread ComputerClient socket new Socket setLayout new FlowLayout Box box Box createVerticalBox connection new Button 连接服务器 send new Button 发送 send setEnabled false inputText new TextField 12 showResult new TextField 12 box add connection box add new Label 输入三角形三边的长度 用逗号或空格分隔 box add inputText box add send box add new Label 收到的结果 box add showResult connection addActionListener this send addActionListener this thread new Thread this add box setBounds 10 30 300 400 setVisible true validate addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 public void actionPerformed ActionEvent e if e getSource connection try 请求和服务器建立套接字连接 if socket isConnected else InetAddress address InetAddress getByName 127 0 0 1 InetSocketAddress socketAddress new InetSocketAddress address 4331 socket connect socketAddress in new DataInputStream socket getInputStream out new DataOutputStream socket getOutputStream send setEnabled true thread start catch IOException ee if e getSource send String s inputText getText if s null try out writeUTF s catch IOException e1 public void run String s null while true try s in readUTF showResult setText s catch IOException e showResult setText 与服务器已断开 break 2 服务器端 import java io import import java util public class Server public static void main String args ServerSocket server null Server thread thread Socket you null while true try server new ServerSocket 4331 catch IOException e1 System out println 正在监听 ServerSocket 对象不能重复创建 try System out println 等待客户呼叫 you server accept System out println 客户的地址 you getInetAddress catch IOException e System out println 正在等待客户 if you null new Server thread you start 为每个客户启动一个专门的线程 class Server thread extends Thread Socket socket DataOutputStream out null DataInputStream in null String s null boolean quesion false Server thread Socket t socket t try out new DataOutputStream socket getOutputStream in new DataInputStream socket getInputStream catch IOException e public void run while true double a new double 3 int i 0 try s in readUTF 堵塞状态 除非读取到信息 quesion false StringTokenizer fenxi new StringTokenizer s while fenxi hasMoreTokens String temp fenxi nextToken try a i Double valueOf temp doubleValue i catch NumberFormatException e out writeUTF 请输入数字字符 quesion true if quesion false double p a 0 a 1 a 2 2 0 out writeUTF Math sqrt p p a 0 p a 1 p a 2 catch IOException e System out println 客户离开 return 2 客户端 Client java import import java io import java awt import java awt event import javax swing public class Client public static void main String args new ChatClient class ChatClient extends Frame implements Runnable ActionListener Button connection send TextField inputName inputContent TextArea chatResult Socket socket null DataInputStream in null DataOutputStream out null Thread thread String name public ChatClient socket new Socket Box box1 Box createHorizontalBox connection new Button 连接服务器 send new Button 发送 send setEnabled false inputName new TextField 6 inputContent new TextField 22 chatResult new TextArea box1 add new Label 输入妮称 box1 add inputName box1 add connection Box box2 Box createHorizontalBox box2 add new Label 输入聊天内容 box2 add inputContent box2 add send connection addActionListener this send addActionListener this thread new Thread this add box1 BorderLayout NORTH add box2 BorderLayout SOUTH add chatResult BorderLayout CENTER setBounds 10 30 400 280 setVisible true validate addWindowListener new WindowAdapter public void windowClosing WindowEvent e System exit 0 public void actionPerformed ActionEvent e if e getSource connection try if socket isConnected else InetAddress address InetAddress getByName 127 0 0 1 InetSocketAddress socketAddress new InetSocketAddress address 666 socket connect socketAddress in new DataInputStream socket getInputStream out new DataOutputStream socket getOutputStream name inputName getText out writeUTF 姓名 name send setEnabled true if thread isAlive thread new Thread this thread start catch IOException ee if e getSource send String s inputContent getText if s null try out writeUTF 聊天内容 name s catch IOException e1 public void run String s null while true try s in readUTF chatResult append n s catch IOException e chatResult setText 与服务器已断开 try socket close catch Exception exp break 服务器端 ChatServer java import java io import import java util public class ChatServer public static void main String args ServerSocket server null Socket you null Hashtable peopleList peopleList new Hashtable
展开阅读全文
相关资源
相关搜索

当前位置:首页 > 办公文档 > 解决方案


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!