Java语言程序设计郑莉第八章课后习地的题目详解
Java语言程序设计第九版第八章答案
![Java语言程序设计第九版第八章答案](https://img.taocdn.com/s3/m/a96da15090c69ec3d4bb7520.png)
Chapter 8 Objects and Classes1. See the section "Defining Classes for Objects."2. The syntax to define a class ispublic class ClassName {}3.The syntax to declare a reference variable for an object isClassName v;4.The syntax to create an object isnew ClassName();5. Constructors are special kinds of methods that are called when creating an objectusing the new operator. Constructors do not have a return type—not even void.6. A class has a default constructor only if the class does not define any constructor.7. The member access operator is used to access a data field or invoke a method froman object.8.An anonymous object is the one that does not have a reference variable referencing it.9.A NullPointerException occurs when a null reference variable is used to access themembers of an object.10.An array is an object. The default value for the elements of an array is 0 for numeric,false for boolean, ‘\u0000’ for char, null for object element type.11.(a) There is such constructor ShowErrors(int) in the ShowErrors class.The ShowErrors class in the book has a default constructor. It is actually same as public class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors(5);}public ShowErrors () {}}On Line 3, new ShowErrors(5) attempts to create an instance using a constructorShowErrors(int), but the ShowErrors class does not have such a constructor. That is an error.(b) x() is not a method in the ShowErrors class.The ShowErrors class in the book has a default constructor. It is actually same as public class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors();t.x();}public ShowErrors () {}}On Line 4, t.x() is invoked, but the ShowErrors class does not have the methodnamed x(). That is an error.(c) The program compiles fine, but it has a runtime error because variable c is nullwhen the println statement is executed.(d) new C(5.0) does not match any constructors in class C. The program has acompilation error because class C does not have a constructor with a doubleargument.12.The program does not compile because new A() is used in class Test, but class Adoes not have a default constructor. See the second NOTE in the Section,“Constructors.”13.falsee the Date’s no-arg constructor to create a Date for the current time. Use theDate’s toString() method to display a string representation for the Date.e the JFrame’s no-arg constructor to create JFrame. Use the setTitle(String)method a set a title and use the setVisible(true) method to display the frame.16.Date is in java.util. JFrame and JOptionPane are in javax.swing. System and Math arein ng.17. System.out.println(f.i);Answer: CorrectSystem.out.println(f.s);Answer: Correctf.imethod();Answer: Correctf.smethod();Answer: CorrectSystem.out.println(F.i);Answer: IncorrectSystem.out.println(F.s);Answer: CorrectF.imethod();Answer: IncorrectF.smethod();Answer: Correct18. Add static in the main method and in the factorial method because these twomethods don’t need reference any instance objects or invoke any instance methods in the Test class.19. You cannot invoke an instance method or reference an instance variable from a staticmethod. You can invoke a static method or reference a static variable from an instancemethod? c is an instance variable, which cannot be accessed from the static context inmethod2.20. Accessor method is for retrieving private data value and mutator method is for changing private data value. The naming convention for accessor method is getDataFieldName() for non-boolean values and isDataFieldName() for boolean values. The naming convention for mutator method is setDataFieldName(value).21.Two benefits: (1) for protecting data and (2) for easy to maintain the class.22. Not a problem. Though radius is private, myCircle.radius is used inside the Circle class.Thus, it is fine.23. Java uses “pass by value” to pass parameters to a method. When passin g avariable of a primitive type to a method, the variable remains unchanged after themethod finishes. However, when passing a variable of a reference type to a method,any changes to the object referenced by the variable inside the method arepermanent changes to the object referenced by the variable outside of the method.Both the actual parameter and the formal parameter variables reference to the sameobject.The output of the program is as follows:count 101times 024.Remark: The reference value of circle1 is passed to x and the reference value of circle2 is passed to y. The contents of the objects are not swapped in the swap1 method. circle1 and circle2 are not swapped. To actually swap the contents of these objects, replace the following three lines Circle temp = x;x =y;y =temp;bydouble temp = x.radius;x.radius = y.radius;y.radius = temp;as in swap2.25. a. a[0] = 1 a[1] = 2b. a[0] = 2 a[1] = 1c. e1 = 2 e2 = 1d. t1’s i = 2 t1’s j = 1t2’s i = 2 t2’s j = 126. (a) null(b) 1234567(c) 7654321(d) 123456727. (Line 4 prints null since dates[0] is null. Line 5 causes a NullPointerException since it invokes toString() method from the null reference.)本文档部分内容来源于网络,如有内容侵权请告知删除,感谢您的配合!。
java语言程序设计课后习题答案解析
![java语言程序设计课后习题答案解析](https://img.taocdn.com/s3/m/d5e3075e7e21af45b307a8df.png)
习题23.使用“= =”对相同内容的字符串进行比较,看会产生什么样的结果。
答:首先创建一个字符串变量有两种方式:String str = new String("abc");String str = "abc";使用“= =”会因为创建的形式不同而产生不同的结果:String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1= =str2); //falseString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1= =str2); //false因此自符串如果是对内容进行比较,使用equals方法比较可靠。
String str1 = "abc";String str2 = "abc";System.out.println(str1= =str2); //trueString str1 = new String("abc"); String str2 = "abc";System.out.println(str1.equals(str2)); //trueString str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1.equals(str2)); //true5.编写一个程序,把变量n的初始值设置为1678,然后利用除法运算和取余运算把变量的每位数字都提出来并打印,输出结果为:n=1678。
C语言程序的设计(郑莉)课后习题答案
![C语言程序的设计(郑莉)课后习题答案](https://img.taocdn.com/s3/m/f42fe794af45b307e87197f8.png)
C++语言程序设计(清华大学莉)课后习题答案第一章概述1-1 简述计算机程序设计语言的发展历程。
解:迄今为止计算机程序设计语言的发展经历了机器语言、汇编语言、高级语言等阶段,C++语言是一种面向对象的编程语言,也属于高级语言。
1-2 面向对象的编程语言有哪些特点?解:面向对象的编程语言与以往各种编程语言有根本的不同,它设计的出发点就是为了能更直接的描述客观世界中存在的事物以及它们之间的关系。
面向对象的编程语言将客观事物看作具有属性和行为的对象,通过抽象找出同一类对象的共同属性(静态特征)和行为(动态特征),形成类。
通过类的继承与多态可以很方便地实现代码重用,大大缩短了软件开发周期,并使得软件风格统一。
因此,面向对象的编程语言使程序能够比较直接地反问题域的本来面目,软件开发人员能够利用人类认识事物所采用的一般思维方法来进行软件开发。
C++语言是目前应用最广的面向对象的编程语言。
1-3 什么是结构化程序设计方法?这种方法有哪些优点和缺点?解:结构化程序设计的思路是:自顶向下、逐步求精;其程序结构是按功能划分为若干个基本模块;各模块之间的关系尽可能简单,在功能上相对独立;每一模块部均是由顺序、选择和循环三种基本结构组成;其模块化实现的具体方法是使用子程序。
结构化程序设计由于采用了模块分解与功能抽象,自顶向下、分而治之的方法,从而有效地将一个较复杂的程序系统设计任务分解成许多易于控制和处理的子任务,便于开发和维护。
虽然结构化程序设计方法具有很多的优点,但它仍是一种面向过程的程序设计方法,它把数据和处理数据的过程分离为相互独立的实体。
当数据结构改变时,所有相关的处理过程都要进行相应的修改,每一种相对于老问题的新方法都要带来额外的开销,程序的可重用性差。
由于图形用户界面的应用,程序运行由顺序运行演变为事件驱动,使得软件使用起来越来越方便,但开发起来却越来越困难,对这种软件的功能很难用过程来描述和实现,使用面向过程的方法来开发和维护都将非常困难。
C语言程序设计(郑莉)课后习题答案
![C语言程序设计(郑莉)课后习题答案](https://img.taocdn.com/s3/m/8cdee2c4a2161479161128b2.png)
C语言程序设计(郑莉)课后习题答案C++语言程序设计(清华大学郑莉)课后习题答案第一章概述1-1 简述计算机程序设计语言的发展历程。
解:迄今为止计算机程序设计语言的发展经历了机器语言、汇编语言、高级语言等阶段,C++语言是一种面向对象的编程语言,也属于高级语言。
1-2 面向对象的编程语言有哪些特点?解:面向对象的编程语言与以往各种编程语言有根本的不同,它设计的出发点就是为了能更直接的描述客观世界中存在的事物以及它们之间的关系。
面向对象的编程语言将客观事物看作具有属性和行为的对象,通过抽象找出同一类对象的共同属性(静态特征)和行为(动态特征),形成类。
通过类的继承与多态可以很方便地实现代码重用,大大缩短了软件开发周期,并使得软件风格统一。
因此,面向对象的编程语言使程序能够比较直接地反问题域的本来面目,软件开发人员能够利用人类认识事物所采用的一般思维方法来进行软件开发。
C++语言是目前应用最广的面向对象的编程语言。
1-3 什么是结构化程序设计方法?这种方法有哪些优点和缺点?解:结构化程序设计的思路是:自顶向下、逐步求精;其程序结构是按功能划分为若干个基本模块;各模块之间的关系尽可能简单,在功能上相对独立;每一模块内部均是由顺序、选择和循环三种基本结构组成;其模块化实现的具体方法是使用子程序。
结构化程序设计由于采用了模块分解与功能抽象,自顶向下、分而治之的方法,从而有效地将一个较复杂的程序系统设计任务分解成许多易于控制和处理的子任务,便于开发和维护。
虽然结构化程序设计方法具有很多的优点,但它仍是一种面向过程的程序设计方法,它把数据和处理数据的过程分离为相互独立的实体。
当数据结构改变时,所有相关的处理过程都要进行相应的修改,每一种相对于老问题的新方法都要带来额外的开销,程序的可重用性差。
由于图形用户界面的应用,程序运行由顺序运行演变为事件驱动,使得软件使用起来越来越方便,但开发起来却越来越困难,对这种软件的功能很难用过程来描述和实现,使用面向过程的方法来开发和维护都将非常困难。
Java语言程序设计(郑莉)一到八章课后习题答案
![Java语言程序设计(郑莉)一到八章课后习题答案](https://img.taocdn.com/s3/m/4e5da514ff00bed5b9f31d91.png)
第二章习题答案1.什么是对象、类,它们之间的联系?答:1)对象是包含现实世界物体特征的抽象实体,它反映系统为之保存信息和与它交互的能力。
对象是一些属性及服务的封装体,在程序设计领域,可以用“对象=数据+作用于这些数据上的操作”来表示。
现实生活中对象是指客观世界的实体;在程序中对象是指一组变量和相关方法的集合。
2)类是既有相同操作功能和相同的数据格式的对象的集合与抽象!两者的关系:对象是类的具体实例.。
2.什么是面向对象的程序设计方法?它有那些基本特征?答:面向对象程序设计从所处理的数据入手,以数据为中心而不是以服务为中心来描述系统。
它把编程问题视为一个数据集合,数据相对于功能而言,具有更强的稳定性。
它的特征:抽象,封装,继承,多态。
3.在下面的应用中,找出可能用到的对象,对每一个对象,列出可能的状态和行为。
1)模拟航空预订系统交易的程序2)模拟银行交易的程序答:1)航空预订交易:状态:旅客姓名,身份证号,联系号码,出发地址,抵达地址,出发日期。
行为:订票,领票,买票,退票。
2)银行交易:状态:客户姓名,账号,身份证号。
行为:存款,取款,汇款。
4.请解释类属性、实例属性及其区别。
答:实例属性,由一个个的实例用来存储所有实例都需要的属性信息,不同实例的属性值可能会不同。
5.请解释类方法、实例属性及其区别。
答:实例方法表示特定对象的行为,在声明时前面不加static修饰符,在使用时需要发送给一个类实例。
类方法也称为静态方法,在方法声明时前面需加static修饰符,类方法表示具体实例中类对象的共有行为。
区别:实例方法可以直接访问实例变量,调用实例方法,实例方法可以直接访问类变量,调用类方法;类方法可以直接调用类变量和类方法,类方法不能直接调用实例变量和实例方法;6.类的访问控制符有哪几种?具体含义及其区别。
答:类的访问控制符只有public(公共类)及无修饰符(默认类)两种。
区别:当使用public修饰符时表示所有其他的类都可以使用此类;当没有修饰符时,则只有与此类处于同一包中的其他类可以使用类。
Java语言程序设计课后习题答案全集
![Java语言程序设计课后习题答案全集](https://img.taocdn.com/s3/m/b8b2d0d2f9c75fbfc77da26925c52cc58bd690ba.png)
Java语言程序设计课后习题答案全集Java语言程序设计是一门广泛应用于软件开发领域的编程语言,随着其应用范围的不断扩大,对于掌握Java编程技巧的需求也逐渐增加。
为了帮助读者更好地掌握Java编程,本文将提供Java语言程序设计课后习题的全集答案,供读者参考。
一、基础知识题1. 代码中的注释是什么作用?如何使用注释.答:注释在代码中是用来解释或者说明代码的功能或用途的语句,编译器在编译代码时会自动忽略注释。
在Java中,有三种注释的方式:- 单行注释:使用"// " 可以在代码的一行中加入注释。
- 多行注释:使用"/* */" 可以在多行中添加注释。
- 文档注释:使用"/** */" 可以添加方法或类的文档注释。
2. 什么是Java的数据类型?请列举常见的数据类型。
答:Java的数据类型用来指定变量的类型,常见的数据类型有:- 基本数据类型:包括整型(byte、short、int、long)、浮点型(float、double)、字符型(char)、布尔型(boolean)。
- 引用数据类型:包括类(class)、接口(interface)、数组(array)等。
二、代码编写题1. 编写Java程序,输入两个整数,求和并输出结果。
答:```javaimport java.util.Scanner;public class SumCalculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个整数:");int num1 = scanner.nextInt();System.out.print("请输入第二个整数:");int num2 = scanner.nextInt();int sum = num1 + num2;System.out.println("两个整数的和为:" + sum);}}```三、综合应用题1. 编写Java程序,实现学生信息管理系统,要求包括以下功能:- 添加学生信息(姓名、年龄、性别、学号等);- 修改学生信息;- 删除学生信息;- 查询学生信息。
《Java程序设计》课后习题参考答案
![《Java程序设计》课后习题参考答案](https://img.taocdn.com/s3/m/bcf6c471e418964bcf84b9d528ea81c758f52e00.png)
《Java程序设计》课后习题参考答案Java程序设计课后习题参考答案1. 介绍在 Java 程序设计课程中,课后习题是帮助学生巩固知识、加深理解和提高编程能力的重要环节。
本文将为大家提供《Java程序设计》课后习题的参考答案,以帮助学生更好地学习和掌握 Java 编程。
2. 基本概念Java 程序设计课后习题涵盖了从基础到高级的各种知识点,包括但不限于变量、数据类型、条件语句、循环语句、数组、类、对象、继承、多态等内容。
通过解答这些习题,学生可以加深对这些概念的理解,并且通过实际操作来巩固他们的编程能力。
3. 习题解答策略当解答课后习题时,以下几个策略可以帮助你更好地理解和解决问题:3.1 仔细阅读题目要求。
确保自己充分理解题目所要求的功能和目标。
3.2 分析问题。
在着手解答问题之前,先理清思路,分析问题的要点和关键部分。
3.3 设计算法。
根据问题的要求,设计一个合适的算法来解决问题。
3.4 编写代码。
用 Java 编程语言将你设计的算法转化为代码实现。
3.5 测试和调试。
对编写的代码进行测试和调试,确保程序能够正常运行,并且得到正确的结果。
4. 习题参考答案示例下面我们将列举几个常见的习题参考答案示例,以帮助大家更好地理解和学习 Java 程序设计:4.1 变量与数据类型:习题要求定义一个整型变量并赋值为10,然后输出该变量的值。
```public class VariableExample {public static void main(String[] args) {int num = 10;System.out.println("变量的值为:" + num);}}```4.2 条件语句:习题要求判断一个数是否是偶数,如果是,则输出“偶数”,否则输出“奇数”。
```public class EvenOddExample {public static void main(String[] args) {int num = 5;if (num % 2 == 0) {System.out.println("偶数");} else {System.out.println("奇数");}}}```4.3 循环语句:习题要求输出1到10之间的所有偶数。
C语言程序的设计(郑莉)课后习题答案
![C语言程序的设计(郑莉)课后习题答案](https://img.taocdn.com/s3/m/36aa3d65fab069dc51220166.png)
C++语言程序设计(清华大学莉)课后习题答案第一章概述1-1 简述计算机程序设计语言的发展历程。
解:迄今为止计算机程序设计语言的发展经历了机器语言、汇编语言、高级语言等阶段,C++语言是一种面向对象的编程语言,也属于高级语言。
1-2 面向对象的编程语言有哪些特点?解:面向对象的编程语言与以往各种编程语言有根本的不同,它设计的出发点就是为了能更直接的描述客观世界中存在的事物以及它们之间的关系。
面向对象的编程语言将客观事物看作具有属性和行为的对象,通过抽象找出同一类对象的共同属性(静态特征)和行为(动态特征),形成类。
通过类的继承与多态可以很方便地实现代码重用,大大缩短了软件开发周期,并使得软件风格统一。
因此,面向对象的编程语言使程序能够比较直接地反问题域的本来面目,软件开发人员能够利用人类认识事物所采用的一般思维方法来进行软件开发。
C++语言是目前应用最广的面向对象的编程语言。
1-3 什么是结构化程序设计方法?这种方法有哪些优点和缺点?解:结构化程序设计的思路是:自顶向下、逐步求精;其程序结构是按功能划分为若干个基本模块;各模块之间的关系尽可能简单,在功能上相对独立;每一模块部均是由顺序、选择和循环三种基本结构组成;其模块化实现的具体方法是使用子程序。
结构化程序设计由于采用了模块分解与功能抽象,自顶向下、分而治之的方法,从而有效地将一个较复杂的程序系统设计任务分解成许多易于控制和处理的子任务,便于开发和维护。
虽然结构化程序设计方法具有很多的优点,但它仍是一种面向过程的程序设计方法,它把数据和处理数据的过程分离为相互独立的实体。
当数据结构改变时,所有相关的处理过程都要进行相应的修改,每一种相对于老问题的新方法都要带来额外的开销,程序的可重用性差。
由于图形用户界面的应用,程序运行由顺序运行演变为事件驱动,使得软件使用起来越来越方便,但开发起来却越来越困难,对这种软件的功能很难用过程来描述和实现,使用面向过程的方法来开发和维护都将非常困难。
[修订]java语言程序设计基础篇第八章第十题编程参考答案
![[修订]java语言程序设计基础篇第八章第十题编程参考答案](https://img.taocdn.com/s3/m/014eaa2308a1284ac9504378.png)
[修订]java语言程序设计基础篇第八章第十题编程参考答案为二次方程式ax2+bx+c=0设计一个名为QuadraticEquation的类。
这个类包括: 代表三个系数的私有数据域a、b、c。
一个参数为a、b、c的构造方法。
a、b、c的三个get方法。
一个名为getDiscriminant()的方法返回判别式,b2-4ac。
一个名为getRoot1()和getRoot2()的方法返回等式的两个根。
这些方法只有在判别式为非负数时才有用。
如果判别式为负,方法返回0。
画出该类的UML图。
实现这个类。
编写一个测试程序,提示用户输入a、b、c的值,然后显示判别式的结果。
如果判别式为正数,显示两个根;如果判别式为0,显示一个根;否则,显示“The equation has no roots”。
代码:class QuadraticEquation{private int a,b,c;QuadraticEquation(){}public QuadraticEquation(int a,int b,int c){this.a=a;this.b=b;this.c=c;}public int getA(){return a;}public int getB(){return b;}public int getC(){return c;}public int getDiscriminant(){if(b*b-4*a*c>=0)return b*b-4*a*c;elsereturn 0;}public int getRoot1(){if(b*b-4*a*c>=0)return (int)((-b+Math.pow(b*b-4*a*c, 0.5))/(2*a)); elsereturn 0;}public int getRoot2(){if(b*b-4*a*c>=0)return (int)((-b-Math.pow(b*b-4*a*c, 0.5))/(2*a)); elsereturn 0;}}public class XiTi810 {public static void main(String[] args){System.out.println("请输入要计算的方程的系数a、b和c:");java.util.Scanner input =new java.util.Scanner(System.in);System.out.print("a=");int a=input.nextInt();System.out.print("b=");int b=input.nextInt();System.out.print("c=");int c=input.nextInt();QuadraticEquation q=new QuadraticEquation(a,b,c);q.getDiscriminant();if(q.getDiscriminant()>0)System.out.println("它们的根为:"+q.getRoot1()+"和"+q.getRoot2());else if(q.getDiscriminant()==0)System.out.println("此方程只有一个根为:"+q.getRoot1());elseSystem.out.println("方程无解");}}。
Java语言程序设计第九版第八章答案讲课教案
![Java语言程序设计第九版第八章答案讲课教案](https://img.taocdn.com/s3/m/02caca1acc22bcd126ff0cb0.png)
Chapter 8 Objects and Classes1. See the section "Defining Classes for Objects."2. The syntax to define a class ispublic class ClassName {}3.The syntax to declare a reference variable for anobject isClassName v;4.The syntax to create an object isnew ClassName();5. Constructors are special kinds of methods that arecalled when creating an object using the new operator.Constructors do not have a return type—not even void.6. A class has a default constructor only if the classdoes not define any constructor.7. The member access operator is used to access a datafield or invoke a method from an object.8.An anonymous object is the one that does not have areference variable referencing it.9.A NullPointerException occurs when a null referencevariable is used to access the members of an object.10.An array is an object. The default value for theelements of an array is 0 for numeric, false for boolean,‘\u0000’ for char, null for object element type.11.(a) There is such constructor ShowErrors(int) in theShowErrors class.The ShowErrors class in the book has a defaultconstructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors(5);}public ShowErrors () {}}On Line 3, new ShowErrors(5) attempts to create aninstance using a constructor ShowErrors(int), but theShowErrors class does not have such a constructor. That is an error.(b) x() is not a method in the ShowErrors class.The ShowErrors class in the book has a defaultconstructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors();t.x();}public ShowErrors () {}}On Line 4, t.x() is invoked, but the ShowErrors classdoes not have the method named x(). That is an error.(c) The program compiles fine, but it has a runtimeerror because variable c is null when the printlnstatement is executed.(d) new C(5.0) does not match any constructors in classC. The program has a compilation error because class Cdoes not have a constructor with a double argument. 12.The program does not compile because new A() is used inclass Test, but class A does not have a defaultconstructor. See the second NOTE in the Section,“Constructors.”13.falsee the Date’s no-arg constructor to create a Date forthe current time. Use the Date’s toString() method todisplay a string representation for the Date.e the JFrame’s no-arg constructor to create JFrame.Use the setTitle(String) method a set a title and use thesetVisible(true) method to display the frame.16.Date is in java.util. JFrame and JOptionPane are injavax.swing. System and Math are in ng.17. System.out.println(f.i);Answer: CorrectSystem.out.println(f.s);Answer: Correctf.imethod();Answer: Correctf.smethod();Answer: CorrectSystem.out.println(F.i);Answer: IncorrectSystem.out.println(F.s);Answer: CorrectF.imethod();Answer: IncorrectF.smethod();Answer: Correct18. Add static in the main method and in the factorialmethod because these two methods don’t need referenceany instance objects or invoke any instance methods inthe Test class.19. You cannot invoke an instance method or reference aninstance variable from a static method. You can invoke astatic method or reference a static variable from aninstance method? c is an instance variable, which cannot be accessed from the static context in method2.20. Accessor method is for retrieving private data value and mutator method is for changing private data value. The naming convention for accessor method is getDataFieldName() for non-boolean values and isDataFieldName() for boolean values. The naming convention for mutator method is setDataFieldName(value).21.Two benefits: (1) for protecting data and (2) for easyto maintain the class.22. Not a problem. Though radius is private,myCircle.radius is used inside the Circle class. Thus, it is fine.23. Java uses “pass by value” to pass parameters to amethod. When passing a variable of a primitive type toa method, the variable remains unchanged after themethod finishes. However, when passing a variable of areference type to a method, any changes to the objectreferenced by the variable inside the method arepermanent changes to the object referenced by thevariable outside of the method. Both the actualparameter and the formal parameter variables referenceto the same object.The output of the program is as follows:count 101times 024.Remark: The reference value of circle1 is passed to x andthe reference value of circle2 is passed to y. The contents ofthe objects are not swapped in the swap1 method. circle1 andcircle2 are not swapped. To actually swap the contents of these objects, replace the following three linesCircle temp = x;x =y;y =temp;bydouble temp = x.radius;x.radius = y.radius;y.radius = temp;as in swap2.25. a. a[0] = 1 a[1] = 2b. a[0] = 2 a[1] = 1c. e1 = 2 e2 = 1d. t1’s i = 2 t1’s j = 1t2’s i = 2 t2’s j = 126. (a) null(b) 1234567(c) 7654321(d) 123456727. (Line 4 prints null since dates[0] is null. Line 5 causes a NullPointerException since it invokes toString() method from the null reference.)。
JAVA第八章课后习题解答
![JAVA第八章课后习题解答](https://img.taocdn.com/s3/m/1b31882483c4bb4cf7ecd1b2.png)
sb.append('\n'); }
} catch (Exception e) { e.printStackTrace(); } //显示 System.out.println(sb.toString()); } public void copy(){ try { FileWriter fw=new FileWriter(fileCopy); BufferedWriter bw=new BufferedWriter(fw); //写数据流 bw.write(sb.toString(),0,sb.toString().length()); bw.flush(); } catch (Exception e) { e.printStackTrace(); } } //test public static void main(String[] args){ FileDisplayAndCopy fda=new FileDisplayAndCopy("d:\\a.txt","d:\\b.txt"); fda.display(); fda.copy(); } } 【8】建立一个文本文件,输入一段短文,编写一个程序,统计文件中字符的个数,并将结 果写入另一个文件 [解答]: import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; /** * 统计文件中字符的个数,并将结果写入另一个文件 */ public class FileCharCounter {
数据可以是未经加工的原始二进制数据也可以是经一定编码处理后符合某种格式规定的特定数据java据流有字节流和字符流之分
Java语言程序设计第九版第八章答案
![Java语言程序设计第九版第八章答案](https://img.taocdn.com/s3/m/7ce95a43f524ccbff02184d3.png)
J a v a语言程序设计第九版第八章答案(总4页)--本页仅作为文档封面,使用时请直接删除即可----内页可以根据需求调整合适字体及大小--Chapter 8 Objects and Classes1. See the section "Defining Classes for Objects."2. The syntax to define a class ispublic class ClassName {}3.The syntax to declare a reference variable for an object isClassName v;4.The syntax to create an object isnew ClassName();5. Constructors are special kinds of methods that are called whencreating an object using the new operator. Constructors do nothave a return type—not even void.6. A class has a default constructor only if the class does notdefine any constructor.7. The member access operator is used to access a data field orinvoke a method from an object.8.An anonymous object is the one that does not have a referencevariable referencing it.9. A NullPointerException occurs when a null reference variable is usedto access the members of an object.10.An array is an object. The default value for the elements of an arrayis 0 for numeric, false for boolean, ‘\u0000’ for char, null forobject element type.11.(a) There is such constructor ShowErrors(int) in the ShowErrors class.The ShowErrors class in the book has a default constructor. It isactually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors(5);}public ShowErrors () {}}On Line 3, new ShowErrors(5) attempts to create an instance usinga constructor ShowErrors(int), but the ShowErrors class does nothave such a constructor. That is an error.(b) x() is not a method in the ShowErrors class.The ShowErrors class in the book has a default constructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors();();}public ShowErrors () {}}On Line 4, () is invoked, but the ShowErrors class does not have the method named x(). That is an error.(c) The program compiles fine, but it has a runtime error becausevariable c is null when the println statement is executed.(d) new C does not match any constructors in class C. The programhas a compilation error because class C does not have aconstructor with a double argument.12.The program does not compile because new A() is used in class Test,but class A does not have a default constructor. See the second NOTEin the Section, “Constructors.”13.falsee the Date’s no-arg constructor to create a Date for the currenttime. Use the Date’s toString() method to display a stringrepresentation for the Date.e the JFrame’s no-arg constructor to create JFrame. Use thesetTitle(String) method a set a title and use the setVisible(true)method to display the frame.16.Date is in . JFrame and JOptionPane are in . System and Math are in .17. Answer: CorrectAnswer: Correct();Answer: Correct();Answer: CorrectAnswer: IncorrectAnswer: Correct();Answer: Incorrect();Answer: Correct18. Add static in the main method and in the factorial method becausethese two methods don’t need reference any instance objects orinvoke any instance methods in the Test class.19. You cannot invoke an instance method or reference an instancevariable from a static method. You can invoke a static method orreference a static variable from an instance method c is an instancevariable, which cannot be accessed from the static context in method2.20. Accessor method is for retrieving private data value and mutator method is for changing private data value. The naming convention for accessor method is getDataFieldName() for non-boolean values and isDataFieldName() for boolean values. The naming convention for mutator method issetDataFieldName(value).21. Two benefits: (1) for protecting data and (2) for easy to maintainthe class.22. Not a problem. Though radius is private, is used inside the Circleclass. Thus, it is fine.23. Java uses “pass by value” to pass parameters to a method. Whenpassing a variable of a primitive type to a method, the variableremains unchanged after the method finishes. However, when passinga variable of a reference type to a method, any changes to theobject referenced by the variable inside the method are permanentchanges to the object referenced by the variable outside of themethod. Both the actual parameter and the formal parametervariables reference to the same object.The output of the program is as follows:count 101times 024.Remark: The reference value of circle1 is passed to x and the reference value of circle2 is passed to y. The contents of the objects are not swappedin the swap1 method. circle1 and circle2 are not swapped. To actually swap the contents of these objects, replace the following three linesCircle temp = x;x =y;y =temp;bydouble temp = ;= ;= temp;as in swap2.25. a. a[0] = 1 a[1] = 2b. a[0] = 2 a[1] = 1c. e1 = 2 e2 = 1d. t1’s i = 2 t1’s j = 1t2’s i = 2 t2’s j = 126. (a) null(b) 1234567(c) 7654321(d) 123456727. (Line 4 prints null since dates[0] is null. Line 5 causes a NullPointerException since it invokes toString() method from the null reference.)。
Java语言程序设计郑莉第八章课后习地的题目详解
![Java语言程序设计郑莉第八章课后习地的题目详解](https://img.taocdn.com/s3/m/efd4e2c67c1cfad6195fa768.png)
Java语言程序设计第八章课后习题答案1.进程和线程有何区别,Java是如何实现多线程的。
答:区别:一个程序至少有一个进程,一个进程至少有一个线程;线程的划分尺度小于进程;进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。
Java程序一般是继承Thread 类或者实现 Runnable接口,从而实现多线程。
2.简述线程的生命周期,重点注意线程阻塞的几种情况,以及如何重回就绪状态。
答:线程的声明周期:新建-就绪-(阻塞)-运行--死亡线程阻塞的情况:休眠、进入对象wait池等待、进入对象lock池等待;休眠时间到回到就绪状态;在wait池中获得notify()进入lock池,然后获得锁棋标进入就绪状态。
3.随便选择两个城市作为预选旅游目标。
实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000毫秒以内),哪个先显示完毕,就决定去哪个城市。
分别用Runnable接口和Thread类实现。
(注:两个类,相同一个测试类)//Runnable接口实现的线程runable类public class runnable implements Runnable {private String city;public runnable() {}public runnable(String city) {this.city = city;}public void run() {for (int i = 0; i < 10; i++) {System.out.println(city);try {//休眠1000毫秒。
Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}// Thread类实现的线程thread类public class runnable extends Thread {private String city;public runnable() {}public runnable(String city) {this.city = city;}public void run() {for (int i = 0; i < 10; i++) {System.out.println(city);try {//休眠1000毫秒。
Java语言程序设计第九版第八章答案
![Java语言程序设计第九版第八章答案](https://img.taocdn.com/s3/m/2da8720680eb6294dc886c8a.png)
Chapter 8 Objects and Classes1. See the section "Defining Classes for Objects."2. The syntax to define a class ispublic class ClassName {}3.The syntax todeclare a reference variable for an objectisClassName v;4.The syntax to create an object isnew ClassName();5. Constructors are special kinds of methods that arecalled when creating an object using the new operator.Constructors do not have a return type—not even void.6. A class has a default constructor only if the classdoes not define any constructor.7. The member access operator is used to access a datafield or invoke a method from an object.8.An anonymous object is the one that does not have areference variable referencing it.9.A NullPointerException occurs when a null referencevariable is used to access the members of an object.10.An array is an object. The default value for theelements of an array is 0 for numeric, false for boolean,‘\u0000’ for char, null for object element type.11.(a) There is such constructor ShowErrors(int) in theShowErrors class.The ShowErrors class in the book has a defaultconstructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors(5);}public ShowErrors () {}}On Line 3, new ShowErrors(5) attempts to create aninstance using a constructor ShowErrors(int), but theShowErrors class does not have such a constructor. Thatis an error.(b) x() is not a method in the ShowErrors class.The ShowErrors class in the book has a defaultconstructor. It is actually same aspublic class ShowErrors {public static void main(String[] args) {ShowErrors t = new ShowErrors();t.x();}public ShowErrors () {}}On Line 4, t.x() is invoked, but the ShowErrors classdoes not have the method named x(). That is an error.(c) The program compiles fine, but it has a runtimeerror because variable c is nullwhen the printlnstatement is executed.(d) new C(5.0) does not match any constructors in classC. The program has a compilation error because class Cdoes not have a constructor with a double argument.12.The program does not compile because new A() is used inclass Test, but class A does not have a defaultconstructor. See the second NOTE in the Section,“Constructors.”13.falsee the Date’s no-arg constructor to create a Date forthe current time. Use the Date’s toString() method todisplay a string representation for the Date.e the JFrame’s no-arg constructor to create JFrame.Use the setTitle(String) method a set a title and use thesetVisible(true) method to display the frame.16.Date is in java.util. JFrame and JOptionPane are injavax.swing. System and Math are in ng.17. System.out.println(f.i);Answer: CorrectSystem.out.println(f.s);Answer: Correctf.imethod();Answer: Correctf.smethod();Answer: CorrectSystem.out.println(F.i);Answer: IncorrectSystem.out.println(F.s);Answer: CorrectF.imethod();Answer: IncorrectF.smethod();Answer: Correct18. Add static in the main method and in the factorialmethod beca use these two methods don’t need referenceany instance objects or invoke any instance methods inthe Test class.19. You cannot invoke an instance method or reference aninstance variable from a static method. You can invoke astatic method or reference a static variable from aninstance method? c is an instance variable, which cannot be accessed from the static context in method2.20. Accessor method is for retrieving private data value and mutator method is for changing private data value. The naming convention for accessor method is getDataFieldName() for non-boolean values and isDataFieldName() for boolean values. The naming convention for mutator method is setDataFieldName(value).21.T wo benefits: (1) for protecting data and (2) for easyto maintain the class.22. Not a problem. Though radius is private,myCircle.radius is used inside the Circle class. Thus, it is fine.23. Java uses “pass by value” to pass parameters to amethod. When passing a variable of a primitive type toa method, the variable remains unchanged after themethod finishes. However, when passing a variable of areference type to a method, any changes to the objectreferenced by the variable inside the method arepermanent changes to the object referenced by thevariable outside of the method. Both the actualparameter and the formal parameter variables referenceto the same object.The output of the program is as follows:count 101times 024.Remark: The reference value of circle1 is passed to x andthe reference value of circle2 is passed to y. The contents ofthe objects are not swapped in the swap1 method. circle1 andcircle2 are not swapped. To actually swap the contents of these objects, replace the following three linesCircle temp = x;x =y;y =temp;bydouble temp = x.radius;x.radius = y.radius;y.radius = temp;as in swap2.25. a. a[0] = 1 a[1] = 2b. a[0] = 2 a[1] = 1c. e1 = 2 e2 = 1d. t1’s i = 2 t1’s j = 1t2’s i = 2 t2’s j = 126. (a) null(b) 1234567(c) 7654321(d) 123456727. (Line 4 prints null since dates[0] is null. Line 5 causes a NullPointerException since it invokes toString() method from the null reference.)。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Java语言程序设计第八章课后习题答案1.进程和线程有何区别,Java是如何实现多线程的。
答:区别:一个程序至少有一个进程,一个进程至少有一个线程;线程的划分尺度小于进程;进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。
Java程序一般是继承Thread 类或者实现Runnable接口,从而实现多线程。
2.简述线程的生命周期,重点注意线程阻塞的几种情况,以及如何重回就绪状态。
答:线程的声明周期:新建-就绪-(阻塞)-运行--死亡线程阻塞的情况:休眠、进入对象wait池等待、进入对象lock池等待;休眠时间到回到就绪状态;在wait池中获得notify()进入lock池,然后获得锁棋标进入就绪状态。
3.随便选择两个城市作为预选旅游目标。
实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000毫秒以内),哪个先显示完毕,就决定去哪个城市。
分别用Runnable接口和Thread类实现。
(注:两个类,相同一个测试类)//Runnable接口实现的线程runable类public class runnable implements Runnable {private String city;public runnable() {}public runnable(String city) {this.city = city;}public void run() {for (int i = 0; i < 10; i++) {System.out.println(city);try {//休眠1000毫秒。
Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}// Thread类实现的线程thread类public class runnable extends Thread { private String city;public runnable() {}public runnable(String city) {this.city = city;}public void run() {for (int i = 0; i < 10; i++) {System.out.println(city);try {//休眠1000毫秒。
Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}//test8_3public class test8_3 {public static void main(String[] args) {// 将创建一个线程对象,这个对象接受一个实现了Runnable接口。
实际上这里也就是使用run()方法runnable r1=new runnable("广州");runnable r2=new runnable("乌鲁木齐");Thread t1 = new Thread(r1);Thread t2 = new Thread(r2);// 启动线程t1.start();t2.start();}}运行结果分别为:4.编写一个多线程程序实现如下功能:线程A和线程B分别在屏幕上显示信息“…start”后,调用wait等待;线程C开始后调用sleep休眠一段时间,然后调用notifyall,使线程A和线程B继续运行。
线程A和线程B恢复运行后输出信息“…end”后结束,线程C在判断线程B和线程A结束后自己结束运行。
//test8_4public class test8_4 {Thread A = new Thread("A") {public void run() {Wait("A");}};Thread B = new Thread("B") {public void run() {Wait("B");}};Thread C = new Thread("C") {public void run() {while (true) {if (!A.isAlive() && !B.isAlive())return;try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}notifyall();}}};public synchronized void Wait(String name) {System.out.println(name + "..start");try {wait();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(name + "..end");}public synchronized void notifyall() {notifyAll();}public static void main(String args[]) {test8_4 test = new test8_4();//A、B两线程一起输入start和输出end,不过中间有C让线程休眠2秒,没法全部一次性输出,//之后再唤醒,让AB继续输出下半部分endtest.A.start();test.B.start();test.C.start();}}运行结果:5.实现一个数据单元,包括学号和姓名两部分。
编写两个线程,一个线程往数据单元中写,另一个线程往外读。
要求没写一次就往外读一次。
//Data类import java.util.Scanner;public class Data{String studentId;String name;boolean available = false;// 判断是读是写Scanner in = new Scanner(System.in);// 定义一个输入对象public synchronized void read(){if(available)try{wait();}catch(Exception e){}System.out.printf("请输入学号:");try{studentId=in.next();}catch(Exception e){System.out.println("输入学号出错!"); }System.out.printf("请输入姓名:");try{name=in.next();}catch(Exception e){System.out.println("输入姓名出错!");}System.out.println();available=true;notify();}public synchronized void write(){if(!available)try{wait();}catch(Exception e){}System.out.println("输出学生学号:"+studentId+" 姓名:"+name+"\n");available=false;notify();}}//Read类public class Read extends Thread{ Data d1 = null;public Read(Data d){this.d1=d;}public void run(){while(true){d1.read();}}}//Write类class Write extends Thread{Data d2=null;public Write(Data d){this.d2=d;}public void run(){while(true){d2.write();}}}//test8_5类public class test8_5 {public static void main(String[] args){ Data data=new Data();new Read(data).start();new Write(data).start();}}运行结果:6.创建两个不同优先级的线程,都从1数到10000,看看哪个数得快。
(注:线程的优先级别越高低与执行速度没有绝对关系!)//Count类public class Count extends Thread {int which;int n = 10000;public Count(int which){this.which=which;}public void run() {for (int i = 1; i <= n; i++) {if (i == n) {System.out.println(which+"号进程"+ "结束!");}}}}//test8_6public class test8_6 {public static void main(String[] args) {Count count1 = new Count(1);Count count2 = new Count(2);Thread t1 = new Thread(count1);Thread t2 = new Thread(count2);t1.setPriority(2);//1号进程优先级是2t2.setPriority(8);//2号进程优先级是8t1.start();t2.start();}}运行结果:都有可能。
7.编写一个Java程序,以说明较高优先级的线程通过调用sleep方法,使较低优先级的线程获得运行的机会。
(这里可以借鉴课本例8—13)//TestThread类public class TestThread extends Thread {private int tick = 1;private int num;public TestThread(int i) {this.num = i;}public void run() {while (tick < 400000) {tick++;if ((tick % 50000) == 0) {System.out.println("Thread #" + num + ",tick =" + tick);yield();try {sleep(1);} catch (Exception e) {}}}}}//test8_7public class test8_7 {public static void main(String[] args){TestThread[] runners = new TestThread[2];for(int i=0;i<2;i++){runners[i]=new TestThread(i);}runners[0].setPriority(2);runners[1].setPriority(5);for(int i=0;i<2;i++){runners[i].start();}}}运行结果:8.主线程控制新线程的生命,当主线程运行一段时间后,控制新线程死亡,主线程继续运行一段时间后结束。