java语言程序设计基础篇8.9答案
Java语言程序设计第九版第八章答案

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语言程序设计 课后习题+答案

第一章课后习题1.编译Java程序的命令是什么?2.执行Java程序的命令是什么?3.Java应用程序和小程序的区别是什么?4.编写一个application ,实现在屏幕上打印自己名字的功能。
第一章课后习题答案1.编译Java程序的命令是什么?答案:javac 源文件名2.执行Java程序的命令是什么?java 主类名3.Java应用程序和小程序的区别是什么?Java application⏹由Java解释器独立运行字节码⏹由专门的命令行启动程序执行⏹程序中有定义了main()方法的主类Java applet⏹不能独立运行,字节码必须嵌入HTML文档⏹当浏览器调用含applet的Web页面时执行⏹程序中含有java. applet. Applet 类的子类4.编写一个application ,实现在屏幕上打印自己名字的功能。
class Test{public static void main(String[] args){System.out.println(“张三”);}}第二章课后习题(1)一、选择题1.下列变量定义错误的是。
A) int a; B) double b=4.5; C) boolean b=true; D)float f=9.8;2.下列数据类型的精度由高到低的顺序是:a)float,double,int,longb)double,float,int,bytec)byte,long,double,floatd)double,int,float,long3.执行完下列代码后,int a=3;char b='5';char c=(char)(a+b);c的值是?A)’8’ b)53 c)8 d)564.Unicode是一种_____________A) 数据类型 B)java包 C)字符编码 D)java类5.6+5%3+2的值是___________A)2 B)1 C) 9 D)106.下面的逻辑表达式中合法的是__________A)(7+8)&&(9-5) B)(9*5)||(9*7) C)9>6&&8<10 D)(9%4)&&(8*3) 7.java语言中,占用32位存储空间的是__________。
java语言程序设计基础篇(第八版)_完整版

• 这些信息可能需要几个小时、几天、几 个月甚至几年才会被使用。二级存储单 元也称为外存储器,外存或称为辅存。
• 计算机运行的过程,就是顺次执行程序 中指令的过程。计算机的指令以及运行 时数据都是采用二进制数表示的。下面 举一个简单的例子说明计算机的运行。
.
17
1.1.1计算机的组成与运行
.
10
计算程序 原始数据
输入设备
计算结果
输出设备
外存储器
取数
内存
存数
运算器
外
部
设
指令
备
接
口
控制器
指令数据线
控制信号线
图1-1计算机的基本组成
.
11
1.1.1计算机的组成与运行
• 1)输入单元。输入单元是计算机接收信 息的部分。它从各种输入设备读取信息 (数据和计算机程序),并把这些放置 到其它处理信息的单元中。当今计算机 的大多数信息是通过键盘输入的,但也 逐渐出现使用其它许多输入设备来进行 信息输入,如扫描仪、声音输入设备等。
.
6
1.1.1计算机的组成与运行
• 我们操作过计算机的人都知道,计算机 就是一种设备,它能让我们进行文字处 理,绘制图形,玩游戏,听音乐,制作 动画,上网查询信息和观看网络电影, 等等。这是从计算机应用角度上的认识, 实际上,计算机是能够以比人快几百万 甚至几十亿倍的速度执行计算和逻辑判 断的设备。这种说法可能让人感到有点 神奇甚至迷惑:
.
15
1.1.1计算机的组成与运行
• 当要把内存中信息用于计算时,CPU会 把这种请求通知其内部的运算器;当要 把内存中的信息发送给某个输出设备时, CPU就会告诉输出设备。
Java语言程序设计第8章习题参考答案.docx

习题八参考答案1.什么是组件?什么是容器?并说明各自的作用。
答:从实现角度来看,组件(Component)是构成GUI的基本要素,作用是通过对不同事件的响应来完成和用户的交互或组件之间的交互;容器是能容纳和排列组件的对象,如Applet> Panel (面板)、Frame (窗口)等,作用就是放置组件并控制组件位置。
2.简述Swing组件的优点。
答:Swing是在AWT基础上扩展而来的,提供了非常丰富的组件,远远多于AWT,并且引入了新的概念和性能,这使得基于Swing开发GUI应用程序比直接使用AWT开发更为灵活、方便、效率高,而且能设计出更优美的、感受更好的GUI。
3.简述容器的概念,结合8.4.7小节的内容,解释什么是应用程序的主框架?答:容器是用来容纳其他组件和容器的特殊组件,是由容器类(Container类)创建的对象。
在Java语言中,容器类是组件类(组件类Component类)的一个子类,具有组件的所有性质。
在AWT 技术中,容器类由java. awt包提供,主要包括面板类Panel、窗口类Window、结构类Frame、对话框类Dialog等。
在Swing技术中,容器类由javax. swing包提供,并可分为如下三类:>顶层容器:JFramc. JApplet. JDialog、JWindow;>中间容器:JPanel、JScrollPane^ JSplitPane、JDesktopPaneJToolBar;特殊容器:在GUI上起特殊作用的中间层,如J Interna IFrame、JLayeredPane、 JRootPaneo 应用程序的主框架由可以容纳应用程序各种组件的顶层容器创建,除了负责组件的管理外,通常还提供最大化、最小化、关闭按钮等,实现应用程序展现方式以及关闭等。
4.总结JFrame的使用要点,并说明内容面板的作用。
答:JFrame类包含很多设置窗体的方法,可以用setTitle(String tille)方法设置窗体标题,用setBounds(inl x,int y,int width,int height)方法设置窗体显示的位置及大小,用setVisable (Boolean b)方法设置可见与否(默认不可见)。
Java语言程序设计第九版第八章答案

Chapter 8 Objects and Classes1.See the section "Defining Classes for Objects."2.The syntax to define a classis public class ClassName {}3.The syntax to declare a reference variable foran object 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 theclass does not define any constructor.7.The member access operator is used to access adata field or invoke a method from an object.8.An anonymous object is the one that does not havea reference 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 aruntime error because variable c is null when theprintln statement is executed.(d)new C(5.0) does not match any constructors in classC. The program has a compilation error because classC does 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 to display a string representation for the Date.15. Use 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 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 in theTest 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 beaccessed from the static context in method2.20.Accessor method is for retrieving private data value andmutator method is for changing private data value. The namingconvention for accessor method is getDataFieldName() for non-boolean values and isDataFieldName() for boolean values. Thenaming 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, itis fine.23.Java uses “pass by value ” to pass parameters to amethod. When passing a variable of a primitive type to amethod, 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 xand the 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] = 2 b.a[0] = 2 a[1] = 1c. e1 = 2 e2 = 1d. t1 ’s i = 2 t1t2 ’s i = 2 t2’s j = 1’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语言程序设计基础篇第8版课后答案

java语言程序设计基础篇第8版课后答案【篇一:java语言程序设计基础篇第八章第十题编程参考答案】icequation的类。
这个类包括:代表三个系数的私有数据域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)elsereturn 0;}}public class xiti810 {public static void main(string[] args){system.out.println(请输入要计算的方程的系数a、b和c:);java.util.scanner input =newjava.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语言程序设计(第8版)第5章完整答案programming exercises(程序练习题)答案完整版】class exercise01 {public static void main(string[] args) {final int pentagonal_numbers_per_line = 10;final int pentagonal_numbers_to_print = 100;int count = 1;int n = 1;while (count = pentagonal_numbers_to_print) {int pentagonalnumber = getpentagonalnumber(n);n++;if (count % pentagonal_numbers_per_line == 0)system.out.printf(%-7d\n, pentagonalnumber);elsesystem.out.printf(%-7d, pentagonalnumber);count++;}}public static int getpentagonalnumber(int n) {return n * (3 * n - 1) / 2;}}5_2import java.util.scanner;public class exercise02 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter an integersystem.out.print(enter an interger: );long number = input.nextlong();system.out.println(the sum of the digits in + number + is + sumdigits(number)); }public static int sumdigits(long n) {int sum = 0;long remainingn = n;}} do { long digit = remainingn % 10; remainingn = remainingn / 10; sum += digit; } while (remainingn != 0); return sum;第03题import java.util.scanner;public class exercise03 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter an integersystem.out.print(enter an integer: );int number = input.nextint();//display resultsystem.out.println(is + number + a palindrome? + ispalindrome(number)); }public static boolean ispalindrome(int number) {if (number == reverse(number))return true;elsereturn false;}public static int reverse(int number) {int reversenumber = 0;do {int digit = number % 10;number = number / 10;reversenumber = reversenumber * 10 + digit;} while (number != 0);return reversenumber;}第04题import java.util.scanner;public class exercise04 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter an integersystem.out.print(enter an integer: );int number = input.nextint();//display resultsystem.out.print(the reversal of + number + is );reverse(number);}public static void reverse(int number) {int reversenumber = 0;do {int digit = number % 10;number = number / 10;reversenumber = reversenumber * 10 + digit;} while (number != 0);system.out.println(reversenumber);}}第05题import java.util.scanner;public class exercise05 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter three numberssystem.out.print(enter three numbers: );double num1 = input.nextdouble();}double num3 = input.nextdouble(); system.out.print(num1 + + num2 + + num3 + in increasing order: ); displaysortednumbers(num1, num2, num3); } public static void displaysortednumbers(double num1, double num2, double num3) { double max = math.max(math.max(num1,num2), num3); double min = math.min(math.min(num1, num2), num3); double second = 0; if (num1 != max num1 !=min)second = num1; if (num2 != max num2 != min)second = num2; if (num3 != max num3 != min)second = num3; system.out.println(min + + second + + max); }5.6import java.util.scanner;public class exercise06 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter an integersystem.out.print(enter an integer: );int number = input.nextint();displaypattern(number);}public static void displaypattern(int n) {int i;int j;for (i = 1; i = n; i++) {for (j = 0; j n - i; j++)system.out.print( );}} for (j = 0; j = i - 1; j++) system.out.printf(%-5d, i - j); system.out.println(); }5.7import java.util.scanner;public class exercise07 {public static void main(string[] args) {scanner input = new scanner(system.in);//prompt the user to enter investment amountsystem.out.print(enter the investment amount: );double investmentamount = input.nextdouble();//prompt the user to enter interest ratesystem.out.print(enter the annual interest rate: );double annualinterestrate = input.nextdouble();//prompt the user to enter yearssystem.out.print(enter number of years: );int years = input.nextint();system.out.println(\nthe amount invested: + investmentamount);system.out.println(annual interest rate: + annualinterestrate + %);system.out.println(years\tfuture value);for (int i = 1; i = years; i++) {system.out.print(i + \t);system.out.printf(%10.2f\n,futureinvestmentvalue(investmentamount, annualinterestrate / 1200, i));}}public static double futureinvestmentvalue(double investmentamount, double monthinterestrate, int years) {return investmentamount * math.pow(1 + monthinterestrate, years * 12);}}【篇三:java语言程序设计基础篇前三章课后习题】s=txt>1.1(显示三条消息)编写程序,显示welcome to java、welcome to computer science和programming is fun。
Java程序设计 第8章习题参考答案[2页]
![Java程序设计 第8章习题参考答案[2页]](https://img.taocdn.com/s3/m/279f7cf1f605cc1755270722192e453610665b0d.png)
第8章习题参考答案一、简答题1.实现类的继承是通过哪个关键字实现的?使用extends 和implements 这两个关键字来实现继承,而且所有的类都是继承于ng.Object,当一个类没有继承的两个关键字,则默认继承object(这个类在ng 包中,所以不需要import祖先类。
在Java 中,类的继承是单一继承,也就是说,一个子类只能拥有一个父类,所以extends 只能继承一个类。
2.Java能实现多继承关系吗?如何解决这个问题?在Java 中,类的继承是单一继承,也就是说,一个子类只能拥有一个父类,所以extends 只能继承一个类。
使用implements 关键字可以变相的使java具有多继承的特性,使用范围为类继承接口的情况,可以同时继承多个接口,接口跟接口之间采用逗号分隔。
3.如果父类和子类同时提供了同名方法,在类实例化后,调用的是哪个类的方法?采用什么办法避免混淆?子类。
通过super 与this 关键字区别父类和子类。
super关键字:我们可以通过super关键字来实现对父类成员的访问,用来引用当前对象的父类。
this关键字:指向自己的引用,表示当前正在调用此方法的对象引用。
4.什么是抽象类?抽象类和普通类有什么不同?抽象类是指类中含有抽象方法的类,抽象类和普通类区别是:1、和普通类比较起来,抽象类它不可以被实例化,这个区别还是非常明显的。
2、抽象类能够有构造函数,被继承的时候,子类就一定要继承父类的一个构造方法,但是,抽象方法不可以被声明成静态。
3、在抽象类当中,可以允许普通方法有主体,抽象方法只需要申明,不需要实现。
4、含有抽象方法的类,必须要申明为抽象类。
5、抽象的子类必须要实现抽象类当中的所有抽象方法,否则的话,这个子类也是抽象类。
6、抽象类它一定要有abstract关键词修饰。
java语言程序设计基础篇第八版复习题答案

java语言程序设计基础篇第八版复习题答案Java语言程序设计基础篇第八版复习题答案# 开始语复习题是检验学习效果的重要手段,以下是针对《Java语言程序设计基础篇第八版》的一些复习题答案,旨在帮助同学们巩固和检验所学知识。
# 复习题及答案1. 简述Java语言的特点。
答案:Java是一种面向对象的编程语言,具有跨平台性、安全性、健壮性、多线程等特点。
它通过Java虚拟机(JVM)实现“一次编写,到处运行”的口号。
2. 什么是面向对象编程(OOP)?答案:面向对象编程是一种编程范式,它使用“对象”来设计软件,这些对象可以包含数据(属性)和代码(方法)。
OOP的核心概念包括封装、继承和多态。
3. 解释Java中的封装、继承和多态。
答案:- 封装:隐藏对象的内部状态和实现细节,只暴露有限的操作界面。
- 继承:允许一个类(子类)继承另一个类(父类)的属性和方法。
- 多态:允许不同类的对象对同一消息做出响应,但具体的行为会根据对象的实际类型而有所不同。
4. 描述Java中的基本数据类型及其范围。
答案:Java中的基本数据类型包括:- `byte`:8位有符号整数,范围从 -128 到 127。
- `short`:16位有符号整数,范围从 -32,768 到 32,767。
- `int`:32位有符号整数,默认类型,范围从 -2^31 到 2^31-1。
- `long`:64位有符号整数,范围从 -2^63 到 2^63-1,必须以 L 或l 结尾。
- `float`:32位单精度浮点数。
- `double`:64位双精度浮点数,默认浮点数类型。
- `char`:16位Unicode字符。
- `boolean`:只有两个可能的值:true 和 false。
- `void`:表示没有任何值。
5. 什么是Java的自动装箱和拆箱?答案:自动装箱是Java自动将基本数据类型转换为对应的包装类的过程,例如将`int`转换为`Integer`。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
在一个正n边形中,所以边的长度都相同,且所有角的度数都相同(即这个多边形是等边等角的)。
设计一个名为RegularPolygon的类,该类包括:
一个名为int型的私有数据域定义多边形的边数,默认值3。
一个名为side的double型私有数据域存储边的长度,默认值1。
一个名为x的double型私有数据域,它定义多边形中点的x坐标,默认值0。
一个名为y 的double型私有数据域,它定义多边形中点的y坐标,默认值0。
一个创建带默认值的正多边形的无参构造方法。
一个能创建带指定边数和边长度、中心在(0,0)的正多边形的构造方法。
一个能创建带指定边数和边长度、中心在(x,y)的正多边形的构造方法。
所有数据域的访问器和修改器。
一个返回多边形周长的方法getPerimeter()。
一个返回多边形面积的方法getArea().计算多边形面积的公式是:面积=(n*s*s)/(4*tan(p/n)) 画出该类的UML图。
实现这个类。
编写一个测试程序,分别使用无参构造方法、RegularPolygon(6,4)和RegularPolygon(10,4,5.6,7.8)创建三个RegularPolygon对象。
显示每个对象的周长和面积。
代码:
class Regularpolygon{
private int n=3;//边长
private double side=1;//边长
private double x=0;
private double y=0;//x,y为多边形中点的x,y坐标
Regularpolygon(){
}
Regularpolygon(int newN,int newS){
n=newN;
side=newS;
x=0;
y=0;
}
Regularpolygon(int newN,int newS,double newX,double newY){
n=newN;
side=newS;
x=newX;
y=newY;
}
public void setN(int newN){
n=newN;
}
public void setSide(double newS){
side=newS;
}
public void setX(double newX){
x=newX;
}
public void setY(double newY){
y=newY;
}
public int getN(){
return n;
}
public double getSide(){
return side;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public double getPerimeter(){
return n*side;
}
public double getArea(){
return (n*side*side)/(4*Math.tan(getPerimeter()/n));
}
}
public class XiTi89 {
public static void main(String[] args){
Regularpolygon r1=new Regularpolygon();
System.out.println(r1);
System.out.println("对象一周长:"+r1.getPerimeter()+" 面积:"+r1.getArea());
Regularpolygon r2=new Regularpolygon(6,4);
System.out.println("对象二周长:"+r2.getPerimeter()+" 面积:"+r2.getArea());
Regularpolygon r3=new Regularpolygon(10,4,5.6,7.8);
System.out.println("对象三周长:"+r3.getPerimeter()+" 面积:"+r3.getArea()); }
}。