Java实战经典(第九、十一章课后题答案)
- 格式:pdf
- 大小:410.89 KB
- 文档页数:8
java开发实战经典课后习题答案Java开发实战经典课后习题答案Java是一种广泛应用于软件开发领域的编程语言,它的特点是简单易学、面向对象、跨平台等。
对于学习Java开发的人来说,掌握实战经典课后习题的答案是提高编程能力的重要途径。
本文将为大家提供一些Java开发实战经典课后习题的答案,希望能够帮助读者更好地理解和掌握Java编程。
一、基础题目1. 编写一个Java程序,输出"Hello, World!"。
```javapublic class HelloWorld {public static void main(String[] args) {System.out.println("Hello, World!");}}```2. 编写一个Java程序,计算1到100之间所有奇数的和。
```javapublic class SumOfOddNumbers {public static void main(String[] args) {int sum = 0;for (int i = 1; i <= 100; i += 2) {sum += i;System.out.println("1到100之间所有奇数的和为:" + sum); }}```3. 编写一个Java程序,判断一个数是否为素数。
```javapublic class PrimeNumber {public static void main(String[] args) {int num = 17;boolean isPrime = true;for (int i = 2; i <= Math.sqrt(num); i++) {if (num % i == 0) {isPrime = false;break;}}if (isPrime) {System.out.println(num + "是素数");} else {System.out.println(num + "不是素数");}}```二、进阶题目1. 编写一个Java程序,实现冒泡排序算法。
11.1、线程的概念:Thread 每个正在系统上运行的程序都是一个进程。
每个进程包含一到多个线程。
进程也可能是整个程序或者是部分程序的动态执行。
线程是一组指令的集合,或者是程序的特殊段,它可以在程序里独立执行。
也可以把它理解为代码运行的上下文。
所以线程基本上是轻量级的进程,它负责在单个程序里执行多任务。
通常由操作系统负责多个线程的调度和执行。
多线程的概念:多线程是为了同步完成多项任务,不是为了提高运行效率,而是为了提高资源使用效率来提高系统的效率。
线程是在同一时间需要完成多项任务的时候实现的。
多线程的优点:使用线程可以把占据长时间的程序中的任务放到后台去处理用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度·11.2、答:一个线程从创建到不再有用称为线程的生命周期。
线程的生命周期可以分为4个状态:①创建(new)状态;②可运行(runnable)状态;⑧不可运行(not runnable)状态;④消亡(dead)状态。
创建状态是指创建一个线程所对应的对象的过程。
Java系统中,这些对象都是从java. lang包内一个称为Thread的类用关键字new创建的。
刚创建的线程不能执行,必须向系统进行注册、分配必要的资源后才能进入可运行状态,这个步骤是由start操作完成的。
而处于可运行状态的线程也未必一定处于运行中,它有可能由于外部的I/O请求而处于不可运行状态。
进入消亡状态后,此线程就不再存在了。
答:一个线程创建之后,总是处于其生命周期的4个状态之一中。
线程的状态表明此线程当前正在进行的活动,而线程的状态是可以通过程序来进行控制的,就是说,可以对线程进行操作来改变状态。
这些操作包括启动(start)、终止(stop)、睡眠(sleep)、挂起(suspend)、恢复(resume)、等待(wait)和通知(notify)。
每一个操作都对应了一个方法,这些方法是由软件包ng提供的。
第9章习题1.异常控制当一个异常发生后,Java 运行系统如何处理? 当异常发生后,由 Java 虚拟机感知到而创建一个 Throwable 或者其子类的一个对象抛出,或者是应用程序执行时感知,而由应用程序创建一个异常对象通过执行 throw 语句抛出 处理,具体方法一般有两种: 1) 2) 将可能发生异常的语句包含在一个 try/catch 块中进行捕获处理。
在方法声明时,声明该方法抛出异常,由调用该方法的代码接受处理,则方法本身 不必处理。
9.4.4 节改写了 withDraw()方法,请对应修改程序 9-6,写出修改后的程序。
2.public class Account { private String id; // 用户唯一的id private String name;// 用户名称 private int balance;// 当前余额 private String state;//账户的状态,例如当为loss时表示挂失 public Account(String id, String name, int balance) { super(); this.id = id; = name; this.balance = balance; } public void withDraw(int amount) throws InsufficientFundsException, LossException{ if(amount>this.balance){ throw new InsufficientFundsException(this.balance); } if(state.equals("loss")){ throw new LossException(); } this.balance-=amount; } public static void main(String[] args){ Account acc=new Account("001","徐嘉怡",100);- 164 -try { acc.withDraw(150); } catch (InsufficientFundsException e) { System.out.println("账户余额不足,只剩下:"+acc.getBalance()); } } //其他有关方法,如属性的getter和setter方法请自行添加 }3. 1)设计一个例子能够验证 9.4.5 节中不被允许的情况。
2-2.Java语言的基本数据类型有哪些?引用数据类型有哪些?【答】基本数据类型有:整数类型byte、short、int、long,浮点数类型float、double,字符类型char,布尔类型boolean;引用数据类型包括数组(array)、类(class)和接口(interface)2-14.作为引用数据类型,数组变量与基本数据类型的变量使用时有哪些区别?【答】数组变量与基本数据类型变量不同点在于,存储单元的分配方式不同,两个变量之间的赋值方式也不同。
基本数据类型变量获得存储单元的方式是静态的,声明了变量后系统就为变量分配了存储单元,就可以对变量赋值。
两个变量之间的赋值是值本身。
数组变量的引用赋值,数组变量保存的是数组的引用,即数组占用的一片连续存储空间的首地址及长度特性。
当声明一个数字变量而未申请空间时,变量是未初始化的,没有地址及特性值。
只有申请了存储空间,才能以下标表示数组元素。
3-1 什么是类?什么是对象?他们之间的关系是怎样的?【答】在面向对象的概念中,类是既包括数据又包括作用于数据的一组操作的封装体。
类中的数据称为成员变量,类中的数据操作称为成员方法。
类中的成员变量和成员方法统称为类的成员。
对象是类的实例。
对象与类的关系就像变量与数据类型的关系一样。
是抽象与具体,模板与实例的关系,类是抽象的、是模板,对象是具体的、是实例。
3-2 作为引用数据类型,对象在赋值和方法的参数传递方面与基本数据类型的变量有什么不同?【答】作为引用数据类型,两个对象之间的赋值是引用赋值,对象可被赋值为null。
具体可参见课本第三章图3.1的(d)。
方法声明中形式参数的数据类型,既可以是基本数据类型,也可以是引用数据类型。
如果形式参数的数据类型是基本数据类型,则实际参数向形式参数传递的是值;如果形参的数据类型是引用数据类型,则实参向形参传递的是引用。
同样,方法返回值的数据类型,既可以是基本数据类型,也可以是引用数据类型,两者分别传递值和引用。
Chapter 9 Strings and Text I/O1.s1 == s2 => trues2 == s3 => falses1.equals(s2) => trues2.equals(s3) => truepareTo(s2) => 0pareTo(s3) => 0s1 == s4 => trues1.charAt(0) => Ws1.indexOf('j') => -1s1.indexOf("to") => 8stIndexOf('a') => 14stIndexOf("o", 15) => 9s1.length() => 16s1.substring(5) => me to Java!s1.substring(5, 11) => me tos1.startsWith("Wel") => trues1.endsWith("Java") => trues1.toLowerCase() => welcome to java!s1.toUpperCase()=> WELCOME TO JAVA!" Welcome ".trim() => Welcomes1.replace('o', 'T') => WelcTme tT Java!s1.replaceAll("o", "T") => WelcTme tT Java!s1.replaceFirst("o", "T") => WelcTme tT Java!s1.toCharArray() returns an array of characters consisting of W, e, l, c, o, m, e, , t, o, , J, a, v, a (Note that none of the operation causes the contents of a string to change)2.String s = new String("new string");Answer: CorrectString s3 = s1 + s2;Answer: CorrectString s3 = s1 - s2;Answer: Incorrects1 == s2Answer: Corrects1 >= s2Answer: IncorrectpareTo(s2);Answer: Correctint i = s1.length();Answer: Correctchar c = s1(0);Answer: Incorrectchar c = s1.charAt(s1.length());Answer: Incorrect : it's out of bounds, even if the preceding problem is fixed.3.The output isWelcome to JavaWelcabcme tabc JavaHint: No method in the String class can change the content of the string. String is an immutable class.4.∙Check whether s1 is equal to s2 and assign the result to a Boolean variable isEqual.boolean isEqual = s1.equals(s2);∙Check whether s1 is equal to s2 ignoring case and assign the result to a Boolean variable isEqual.boolean isEqual = s1.equalsIgnoreCase(s2);∙Compare s1 with s2 and assign the result to an int variable x.int x = pareTo(s2);∙Compare s1 with s2 ignoring case and assign the result to an int variable x.int x = pareToIgnoreCase(s2);∙Check whether s1 has prefix "AAA" and assign the result to a Boolean variable b.boolean b = s1.startsWith("AAA");∙Check whether s1 has suffix "AAA" and assign the result to a Boolean variable b.boolean b = s1.endsWith("AAA");∙Assign the length of s1 to an int variable x.int x = s1.length();∙Assign the first character of s1 to a char variable x. char x = s1.charAt(0);∙Create a new string s3 that combines s1 with s2.String s3 = s1 + s2;∙Create a substring of s1 starting from index 1.String s3 = s1.substring(1);∙Create a substring of s1 from index 1 to index 4.String s3 = s1.substring(1, 5);∙Create a new string s3 that converts s1 to lowercase. String s3 = s1.lowercase();∙Create a new string s3 that converts s1 to uppercase. String s3 = s1.uppercase();∙Create a new string s3 that trims blank spaces on both ends of s1.String s3 = s1.trim();∙Replace all occurrence of character e with E in s1 and assign the new string to s3.String s3 = s1.replaceAll(…e‟, …E‟);∙Split "Welcome to Java and HTML" into an array tokens using delimited by a space.String[] tokens = "Welcome to Java and HTML".split(… …);∙Assign the index of the first occurrence of character e in s1 to an int variable x.int x = s1.indexOf(…e…);∙Assign the index of the last occurrence of string abc in s1 to an int variable x.int x = stIndexOf(“abc”);5.No.6.0.e the overloaded static valueOf method in the String class.8.The text is declared in Line 2 as a data field, but redeclared in Line 5 as a localvariable. The local variable is assigned with the string passed to the constructor,but the data field is still null. In Line 10, test.text is null, which causesNullPointerException when invoking the toLowerCase() method.9.The constructor is declared incorrectly. It should not have void.10. A lowercase letter is between ‘a’ and ‘z’. You can use the staticisLowerCase(char) method in the Character class to test if a character is inlowercase. An uppercase letter is between ‘A’ and ‘Z’. You can use the staticisUpperCase(char) method in the Character class to test if a character is inuppercase.11.An alphanumeric character is between ‘0’ and ‘9’, or ‘A’ and ‘Z’, or ‘a’ and ‘z’.You can use the static isLetterOrDigit(char ch) method in the Character class totest if a character is a digit or a letter.12.The StringBuilder class, introduced in JDK 1.5, is similar to StringBuffer exceptthat the update methods in StringBuffer are synchronized.e the StringBuilder’s constructor to create a string buffer for a string, and usethe toString method in StringBuilder class to return a string from a StringBuilder.14.StringBuilder sb = new StringBuilder(s);sb.reverse();s = sb.toString();15.StringBuilder sb = new StringBuilder(s);sb.delete(4, 10);s = sb.toString();16.Both string and string buffer use arrays to hold characters. The array in a string isfixed once a string is created. The array in a string buffer may change if the buffer capacity is changed. To accommodate the change, a new array is created.17.(1) Java is fun(2) JavaHTML(3) Jais funva(4) JHTMLava(5) v(6) 4(7) Jav(8) Ja(9) avaJ(10) JComputera(11) av(12) va18.The output isJavaJava and HTMLNOTE:Inside the method, the statement s = s + " and HTML" creates a new String objects, which is different from the original String object passed to the change(s, buffer)method. The original String object has not been changed. Therefore, the printoutfrom the original string is Java.Inside the method, the content of the StringBuilder object is changed to Java andHTML. Therefore, the printout from buffer is Java and HTML.19.public static void main(String[] args)can be replaced bypublic static void main(String args[])public static void main(String[] x)public static void main(String x[])but notstatic void main(String x[])because it is not public.20.(1)Number of strings is 4Ihaveadream(2)Number of strings is 11 2 3(3)Number of strings is 0(4)Number of strings is 1*(5)Number of strings is (the number of files and directory from where the commandis executed)Displays all files and directory names in the directory where the command isexecuted.21. The \ is a special character. It should be written as \\ in Java using the Escapesequence.e exists() in the File class to check whether a file exists. Use delete() in the Fileclass to delete this file. Use renameTo(File) to rename the name for this file. Youcannot find the file size using the File class.23.No. The File class can be used to obtain file properties and manipulate files, butcannot perform I/O.24.To create a PrintWriter for a file, use new PrintWriter(filename). This statementmay throw an exception. Java forces you to write the code to deal with exceptions.One way to deal with it is to declare throws Exception in the method declaration.If the close() method is not invoked, the data may not be saved properly.25.The contents of the file temp.txt is:amount is 32.320000 3.232000e+01amount is 32.3200 3.2320e+01falseJava26.To create a Scanner for a file, use new Scanner(new File(filename)). This statementmay throw an exception. Java forces you to write the code to deal with exceptions.One way to deal with it is to declare throws Exception in the method declaration.If the close() method is not invoked, the problem will run fine. But it is a goodpractice to close the file to release the resource on the file.27.If you attempt to create a Scanner for a nonexistent file, an exception will occur. Ifyou attempt to create a Formatter for an existing file, the contents of the existingfile will be gone.28.No. The line separator on Windows is \r\n.29.intValue contains 45. doubleValue contains 57.8, andline contains ' ', '7', '8', '9'.30.intValue contains 45. doubleValue contains 57.8, andline is empty.。
第9章习题解答1.与输入/输出有关的流类有哪些?答:与输入/输出有关的流类主要有InputStream、OutputStream和Reader、Writer类及其子类。
除此以外,与流有关的类还有File类、FileDescriptor类、StreamTokenizer类和RandomAccessFile类。
2.字节流与字符流之间有哪些区别?答:字节流是面向字节的流,流中的数据以8位字节为单位进行读写,是抽象类InputStream和OutputStream的子类,通常用于读写二进制数据,如图像和声音。
字符流是面向字符的流,流中的数据以16位字符(Unicode字符)为单位进行读写,是抽象类Reader和Writer的子类,通常用于字符数据的处理。
3.什么是节点流?什么是处理流或过滤流?分别在什么场合使用?答:一个流有两个端点。
一个端点是程序;另一个端点可以是特定的外部设备(如键盘、显示器、已连接的网络等)和磁盘文件,甚至是一块内存区域(统称为节点),也可以是一个已存在流的目的端。
流的一端是程序,另一端是节点的流,称为节点流。
节点流是一种最基本的流。
以其它已经存在的流作为一个端点的流,称为处理流。
处理流又称过滤流,是对已存在的节点流或其它处理流的进一步处理。
对节点流中的数据只能按字节或字符读写。
当读写的数据不是单个字节或字符,而是一个数据块或字符串等时,就要使用处理流或过滤流。
4.标准流对象有哪些?它们是哪个类的对象?答:标准流对象有3个,它们是:System.in、System.out和System.err。
System.in 是InputStream类对象,System.out和System.err是PrintStream类对象。
5.顺序读写与随机读写的特点分别是什么?答:所谓顺序读写是指在读写流中的数据时只能按顺序进行。
换言之,在读取流中的第n个字节或字符时,必须已经读取了流中的前n-1个字节或字符;同样,在写入了流中n-1个字节或字符后,才能写入第n个字节或字符。
第11章作业参考答案
1.填空题TCP/IP
(1)Inet4AddressUDP
(4)应用层(5) Socket
2 .选择
3 .简答题
(1)回答要点
一共有4层,分别是物理+数据链路层、网络层、传输层和应用层。
(2)回答要点
如果把程序当做人,把计算机网络当做类似邮递员的角色,当一个程序需要发送数据时, 指定目的地的IP地址就像指定了目的地的街道或楼号,但这样还是找不到目的地的,还需要指定房间号,也就是端口号。
(3)回答要点
UDP将数据及源和目的封装成数据包中,不需要建立连接,每个数据报的大小在限制在64k内,因无连接,所以是不可靠协议,效率高;TCP需要通过三次握手完成连接,是可靠协议,在连接中能进行大数据量传输,传输前需要建立连接,所以效率低。
(4)回答要点
首先翻开终端,输入命令"netstat-ano”查看占用端口号程序的PID,然后在Windows 资源管理器中通过PID找到该进程,结束进程即可。
(5)回答要点
第一次握手是客户端连接到server, server accept client的请求之后,向client端发送一个消息,相当于说我都准备好了,你连接上我了,这是第二次握手,第3次握手是client向server 发送的,是对第二次握手消息确实认。
这样client和server就开始通讯了。
4.编程题
(1)源代码:参考本章资料文件夹下“作业1”。
(2)源代码:参考本章资料文件夹下“作业2”。
习题11 课后习题答案1.常见网络端口有哪些?答案:在计算机中操作系统内部使用1-1024保留端口号,所以设计应用程序时需选择除此之外的端口。
如:20文件传输协议(默认数据口) ,80全球信息网超文本传输协议(www)。
2.如何连接和读取URL中的资源?答案:(1)通过URLConnection连接WWW:用URL的openStream()方法从网络上读取数据,若要输出数据,用类URLConnection,与URL建立连接,然后对其进行读/写操作。
(2)用URL读取WWW数据资源:在取得一个URL对象后,通过使用URL的openStream()方法,可以获得所需的特定的WWW 资源。
3.什么是套接字?有哪几种套接字?答案:套接字Socket是网络通信的应用程序接口,可以实现客户机与服务器之间的通信。
常用的TCP/IP协议的3种套接字类型有:流套接字(SOCK_STREAM);数据包套接字(SOCK_DGRAM);原始套接字(SOCK_RAW)。
流套接字用于提供面向连接、可靠的数据传输服务。
该服务将保证数据能够实现无差错、无重复发送,并按顺序接收。
数据包套接字提供了一种无连接的服务。
该服务并不能保证数据传输的可靠性,数据有可能在传输过程中丢失或出现数据重复,且无法保证顺序地接收到数据。
原始套接字与标准套接字(标准套接字指的是前面介绍的流套接字和数据包套接字)的区别在于:原始套接字可以读写内核没有处理的IP数据包,而流套接字只能读取TCP协议的数据,数据包套接字只能读取UDP协议的数据。
因此,如果要访问其他协议发送数据必须使用原始套接字。
4.简述TCP套接字的实现过程?答案:实现TCP套接字基本步骤分为服务器端和客户端两部分。
(1)服务器端步骤创建套接字;绑定套接字;设置套接字为监听模式,进入被动接收连接请求状态;接收请求,建立连接;读/写数据;终止连接。
(2)客户端步骤创建套接字;与远程服务器程序连接;读/写数据;终止连接。
J a v a程序设计精编教程(第2版)习题解答(总18页)--本页仅作为文档封面,使用时请直接删除即可----内页可以根据需求调整合适字体及大小--习题解答习题一(第1章)1.James Gosling2.需3个步骤:1) 用文本编辑器编写源文件。
2) 使用javac 编译源文件,得到字节码文件。
3) 使用解释器运行程序。
3.set classpath=D:\jdk\jre\lib\;.;4. B5. Java 源文件的扩展名是.java ,Java 字节码的扩展名是.class 。
6.D 。
习题二(第2章)1.2.public class Teacher {double add(double a,double b) {return a+b;}double sub(double a,double b) {return a-b;}}height bottopublic class Student {public void speak() {"老师好");}}public class MainClass {public static void main(String args[]) {Teacher zhang=new Teacher();Student jiang=new Student();();}}3.如果源文件中有多个类,但没有public类,那么源文件的名字只要和某个类的名字相同,并且扩展名是.java就可以了,如果有一个类是public类,那么源文件的名字必须与这个类的名字完全相同,扩展名是.java。
4.行尾风格。
习题三(第3章)1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。
标识符由字母、下划线、美元符号和数字组成,第一个字符不能是数字。
true不是标识符。
2.关键字就是Java语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来用。