java语言程序设计基础篇8.9答案
- 格式:doc
- 大小:19.00 KB
- 文档页数:2
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.)本文档部分内容来源于网络,如有内容侵权请告知删除,感谢您的配合!。
第一章课后习题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位存储空间的是__________。
习题八参考答案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)方法设置可见与否(默认不可见)。
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语言程序设计基础篇第八章第十题编程参考答案】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。
第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语言程序设计基础篇第八版》的一些复习题答案,旨在帮助同学们巩固和检验所学知识。
# 复习题及答案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`。
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程序设计基础课后习题参考答案第2章1. 关于Java Application 的入口方法main()的检验:main()方法的参数名是否可以改变?main()方法的参数个数是否可以改变?该方法名是否可以改变?参考答案:(1)main()方法的参数名可以改变。
(2)main()方法的参数个数不可以改变。
(3)该方法名不可以改变。
2. 当一个程序没有main()方法时,能编译吗?如果能编译,能运行吗?参考答案:当一个程序没有main()方法是,是可以编译通过的,但是不能给运行,因为找不到一个主函数入口。
3. 下列语句能否编译通过?byte i = 127;byte j = 128;long l1 = 999999;long l2 = 9999999999;参考答案:byte i 和long l1可以编译通过。
而byte j 和long l2 超出自身数据类型范围,所以编译失败。
4. 下列语句能否编译通过?float f1 = 3.5;float f2 = 3.5f;参考答案:java中浮点型的数据在不声明的情况下都是double型的,如果要表示一个数据是float型的,必须在数据后面加上“F”或“f”;因此,float f1 无法编译通过。
5. 验证int 和char,int和double等类型是否可以相互转换。
参考答案:(1)char类型可以转换为int 类型的,但是int类型无法转换为char类型的;(2)int 可以转换为double类型的,但是double类型无法转换为int 类型的。
6. 计算下列表达式,注意观察运算符优先级规则。
若有表达式是非法表达式,则指出不合法之处且进行解释。
(1) 4+5 == 6*2 (2) (4=5)/6(3) 9%2*7/3>17 (4) (4+5)<=6/3(5) 4+5%3!=7-2 (6) 4+5/6>=10%2参考答案:表达式(2)为不合法表达式,只能将值赋值给一个变量,因此其中(4=5)将5赋值给4是不合法的。
J a v a语言程序设计课后习题答案全集Document serial number【UU89WT-UU98YT-UU8CB-UUUT-UUT108】指出JAVA语言的主要特点和JAVA程序的执行过程。
答:(1)强类型;(2)编译和解释;(3)自动无用内存回收功能;(4)面向对象;(5)与平台无关;(6)安全性;(7)分布式计算;(8)多线程;程序执行过程如图所示:编写源文件,编译器编译源文件转换成字节码,解释器执行字节码。
说出开发与运行JAVA程序的重要步骤。
答:(1)编写源文件:使用一个文本编译器,如Edit或记事本,不可以使用Word.将编好的源文件保存起来,源文件的扩展名必须是.java;(2)编译Java源文件:使用Java编译器编译源文件得到字节码文件;(3)运行Java程序:Java程序分为两类——Java应用程序必须通过Java解释器来解释执行其字节码文件;Java小应用程序必须通过支持Java标准的浏览器来解释执行。
如何区分应用程序和小应用程序答:应用程序在与源文件名字相同的类中,有main()方法,该方法代表应用程序的入口; 小应用程序必须有一个Applet类的子类,该类称作主类,必须用public修饰。
说出JAVA源文件的命名规则。
答:源文件命名规则和类命名规则一样,所有的单词首字母都用大写字母,且必须和源文件的public类同名。
JAVA语言使用什么字符集共有多少个不同的字符答:Java语言使用Unicode字符集,共有65535个字符。
JAVA语言标识符的命名规则是什么(1)由字母(包括英文字母、下划线字符、美元字符、文字字符)和数字字符组成(2)限定标识符的第一个字符不能是数字字符(3)不能和关键字重名(4)长度不能超过255个字符JAVA有那些基本数据类型,它们的常量又是如何书写的指出下列内容哪些是JAVA语言的整型常量,哪些是浮点数类型常量,哪些两者都不是。
整型常量: 4)0xABCL,8)003,10)077,12)056L浮点数类型常量:3)-1E-31,5).32E31 13)0.,14).0两者都不是: 1),2),6),7),9),11)第二章 运算和语句Java 的字符能参加算术运算吗可以。
3.4import javax.swing.*;public class AdditionTutor{public static void main(String[] args){int number1=(int)(System.currentTimeMillis()%100);int number2=(int)(System.currentTimeMillis()*5%100);String answerString=JOptionPane.showInputDialog("what is "+ number1 +"+ "+ number2+" ?");int answer=Integer.parseInt(answerString);JOptionPane.showMessageDialog(null,number1 +" + "+ number2 +" = "+answer+" is "+(number1+number2==answer));}}3.10import javax.swing.JOptionPane;public class ComputeTaxWithSelectionStatement{public static void main(String[] args){//Prompt the user to enter filing statusString statusString = JOptionPane.showInputDialog("Enter the filing status:\n"+"(0-single filer,1-married jointly,\n"+"2-married separately,3-head of household)");int status = Integer.parseInt(statusString);//Prompt the user to enter taxable incomeString incomeString = JOptionPane.showInputDialog("Enter the taxable income:");double income = Double.parseDouble(incomeString);//Comput taxdouble tax=0;if (status == 0){//Compute tax for single filersif (income <= 6000)tax = income * 0.10;else if (income <= 27950)tax = 6000 * 0.10 + (income - 6000) * 0.15;else if (income <= 67700)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(income - 27950) * 0.27;else if (income <= 141250)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (income - 67700) * 0.30;else if (income <=307050)tax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (141250 - 67700) * 0.30 +(income - 141250) * 0.35;elsetax = 6000 * 0.10 + (27950 - 6000) * 0.15 +(67700 - 27950) * 0.27 + (141250 -67700) * 0.30 +(307050 - 141250) * 0.35 + (income - 307050) * 0.386;}else if (status == 1){//Compute tax for married file jointly if (income <= 12000)tax = income * 0.10;else if (income <= 46700)tax = 12000 * 0.10 + (income - 12000) * 0.15;else if (income <= 112850)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(income - 46700) * 0.27;else if (income <= 171950)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700) * 0.27 + (income - 112850) * 0.30;else if (income <= 307050)tax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700) * 0.27 + (141250 - 112850) * 0.30 +(income - 307050) * 0.35;elsetax = 12000 * 0.10 + (46700 - 12000) * 0.15 +(112850 - 46700 ) * 0.27 + (171950 - 112850) * 0.30 +(307050 - 171950) * 0.35 + (income - 307050) * 0.386;}else if (status == 2){//Compute tax for married separately if (income <= 6000)tax = income * 0.10;else if (income <= 23350)tax = 6000 * 0.10 + (income - 6000) * 0.15;else if (income <= 56425)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(income - 23350) * 0.27;else if (income <= 85975)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (income - 56425) * 0.30;else if (income <= 153525)tax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (85975 - 56425) * 0.30 +(income - 85975) * 0.35;elsetax = 6000 * 0.10 + (23350 - 6000) * 0.15 +(56425 - 23350) * 0.27 + (85975 - 56425) * 0.30 +(153525 - 85975) * 0.35 + (income - 153525) * 0.386;}else if (status == 3){//Compute tax for head of householdif (income <= 10000)tax = income * 0.10;else if (income <= 37450)tax = 10000 * 0.10 + (income - 10000) * 0.15;else if (income <= 96700)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(income - 37450) * 0.27;else if (income <= 156600)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (income - 96700) * 0.30;else if (income <= 307050)tax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (156600 - 96700) * 0.30 +(income - 156600) * 0.35;elsetax = 10000 * 0.10 + (37450 - 10000) * 0.15 +(96700 - 37450) * 0.27 + (156600 - 96700) * 0.30 +(307050 - 156600) * 0.35 + (income - 307050) * 0.386;}else{System.out.println("Error: invalid status");System.exit(0);}//Display the resultJOptionPane.showMessageDialog(null,"Tax is " +(int)(tax * 100) / 100.0);}}4.11public class ZhengChu{public static void main(String[] args){int count=0;for(int i=100;i<=200;i++){if((i%5==0||i%6==0)&&i%30!=0){System.out.print(" "+ i);count++;if(count%10==0)System.out.println();}}}}4.14public class ASCII{public static void main(String[] args){int count = 0;for(int i = 33; i <= 126; i++){count++;char ch = (char)i;System.out.print(" " + ch);if(count % 10 == 0)System.out.println();}}}4.17import javax.swing.JOptionPane;public class FindSalesAmount{/**Main method*/public static void main(String[] args){//The commission soughtString COMMISSION_SOUGHTString = JOptionPane.showInputDialog("Enter the COMMISSION_SOUGHT :");double COMMISSION_SOUGHT = Double.parseDouble(COMMISSION_SOUGHTString);double commission = 0;double salesAmount;for (salesAmount = 0.01;commission <= COMMISSION_SOUGHT;){salesAmount += 0.01; //防止犯off-by-one错误,先判断在做自加!if (salesAmount >= 10000.01)commission =5000 * 0.08 + 5000 * 0.1 + (salesAmount - 10000) * 0.12;else if (salesAmount >= 5000.01)commission = 5000 * 0.08 + (salesAmount - 5000) * 0.10;elsecommission = salesAmount * 0.08;}String output ="The sales amount $" + (int)(salesAmount * 100) / 100.0 +"\n is needed to make a commission of $" + COMMISSION_SOUGHT;JOptionPane.showMessageDialog(null,output);}}5.6import javax.swing.JOptionPane;public class PrintPyramid{public static void main(String[] args){String input = JOptionPane.showInputDialog("Enter the number of lines:");int numberOfLines = Integer.parseInt(input);displayPattern(numberOfLines);}public static void displayPattern(int n){for (int row = 1;row <= n;row++){for (int column = 1;column <= n - row;column++)System.out.print(" ");for (int num = row;num >= 1;num--)System.out.print((num >= 10) ? " " + num : " " + num);System.out.println();}}}5.18public class MathSuanFa{public static void main(String[] args){double A = Math.sqrt(4);double B = (int)Math.sin(2 * Math.PI);double C = (int)Math.cos(2 * Math.PI);double D = (int)Math.pow(2, 2);double E = (int)Math.log(Math.E);double F = (int)(Math.exp(1)*100000)/100000.0;double G = (int)Math.max(2, Math.min(3, 4));double H = (int)Math.rint(-2.5);double I = (int)Math.ceil(-2.5);double J = (int)Math.floor(-2.5);int K = (int)Math.round(-2.5f);int L = (int)Math.round(-2.5);double M = (int)Math.rint(2.5);double N = (int)Math.ceil(2.5);double O = (int)Math.floor(2.5);int P = (int)Math.round(2.5f);int Q = (int)Math.round(2.5);int R = (int)Math.round(Math.abs(-2.5));System.out.println(A +" "+ B +" "+ C +" "+ D +" "+ E +" "+ F +" "+ G +" "+ H +" "+ I +" "+ J +" "+ K +" "+ L +" "+ M +" "+ N +" "+ O +" "+ P +" "+ Q +" "+ R);}}6.9import javax.swing.JOptionPane;public class Array{public static void main (String[] args){String incomeString = JOptionPane.showInputDialog("Enter the number of array size:");int income = Integer.parseInt(incomeString);int arraySize = income;int [] myList = new int [arraySize];int m;for ( m = 0; m < arraySize; m++){String elementString = JOptionPane.showInputDialog("Enter the " + (m + 1) + " element of the array");int element = Integer.parseInt(elementString);myList[m] = element;}int minElement = myList[0];for (int i=1; i < arraySize; i++){if (myList[i] < minElement)minElement = myList[i];}JOptionPane.showMessageDialog(null,"The min element is: " + minElement); }}。
《Java语言程序设计基础教程》习题解答《Java语言程序设计基础教程》练习思考题参考答案《Java语言程序设计基础教程》22 第1章 Java程序设计概述1.9 练习思考题1、Java运行平台包括三个版本,请选择正确的三项:()A. J2EEB. J2MEC. J2SED. J2E解答:A,B,C2、Java JDK中反编译工具是:()A. javacB. javaC. jdbD. javap解答:D3、public static void main方法的参数描述是:()A. String args[]B. String[] argsC. Strings args[]D. String args解答:A,B4、在Java中,关于CLASSPATH环境变量的说法不正确的是:()A. CLASSPATH一旦设置之后不可修改,但可以将目录添加到该环境变量中。
B. 编译器用它来搜索各自的类文件。
C. CLASSPATH是一个目录列表。
D. 解释器用它来搜索各自的类文件。
解答:A5、编译Java Application源文件将产生相应的字节码文件,扩展名为()A. .javaB. .classC. .htmlD. .exe解答:B6、开发与运行Java程序需要经过的三个主要步骤为____________、____________和____________。
7、如果一个Java Applet源程序文件只定义有一个类,该类的类名为MyApplet,则类MyApplet必须是______类的子类并且存储该源程序文件的文件名为______。
8、如果一个Java Applet程序文件中定义有3个类,则使用Sun 公司的JDK编译器编译该源程序文件将产生______个文件名与类名相同而扩展名为______的字节码文件。
9、开发与运行Java程序需要经过哪些主要步骤和过程?10、Java程序是由什么组成的?一个程序中必须要有public类吗?Java源文件的命名规则是怎么样的?11、编写一个简单的Java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习Java”和“We are students”。
Chapter9Strings 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 Javas1.substring(5,11)=>me tos1.startsWith("Wel")=>trues1.endsWith("Java")=>trues1.toLowerCase()=>welcome to javas1.toUpperCase()=>WELCOME TO JAVA"Welcome".trim()=>Welcomes1.replace('o','T')=>WelcTme tT Javas1.replaceAll("o","T")=>WelcTme tT Javas1.replaceFirst("o","T")=>WelcTme tT Javas1.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 s1is equal to s2and assign the result to a Boolean variable isEqual.boolean isEqual=s1.equals(s2);∙Check whether s1is equal to s2ignoring case and assign the result to a Boolean variable isEqual.boolean isEqual=s1.equalsIgnoreCase(s2);∙Compare s1with s2and assign the result to an int variable x.int x=pareTo(s2);∙Compare s1with s2ignoring case and assign the result to an int variable x.int x=pareToIgnoreCase(s2);∙Check whether s1has prefix"AAA"and assign the result to a Boolean variable b.boolean b=s1.startsWith("AAA");∙Check whether s1has suffix"AAA"and assign the result to a Boolean variable b.boolean b=s1.endsWith("AAA");∙Assign the length of s1to an int variable x.int x=s1.length();∙Assign the first character of s1to a char variable x. char x=s1.charAt(0);∙Create a new string s3that combines s1with s2.String s3=s1+s2;∙Create a substring of s1starting from index 1.String s3=s1.substring(1);∙Create a substring of s1from index1to index 4. String s3=s1.substring(1,5);∙Create a new string s3that converts s1to lowercase. String s3=s1.lowercase();∙Create a new string s3that converts s1to uppercase. String s3=s1.uppercase();∙Create a new string s3that trims blank spaces on both ends of s1.String s3=s1.trim();∙Replace all occurrence of character e with E in s1and 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 charactere in s1to an int variable x.int x=s1.indexOf(‘e‘);Assign the index of the last occurrence of string abc in s1to 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 Line2as a data field,but redeclared in Line5as a localvariable.The local variable is assigned with the string passed to the constructor,but the data field is still null.In Line10,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 JDK1.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 is4Ihaveadream(2)Number of strings is1123(3)Number of strings is0(4)Number of strings is1*(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 e delete()in the Fileclass to delete this e 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 is32.320000 3.232000e+01amount is32.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 contains45.doubleValue contains57.8,andline contains'','7','8','9'.30.intValue contains45.doubleValue contains57.8,andline is empty.。
java语言程序设计基础篇复习题答案【篇一:《java语言程序设计基础教程》(龚永罡—陈昕)习题答案】txt>1.9练习思考题1、a,b,c2、d3、a,b 4 a 5、b6、开发与运行java程序需要经过的三个主要步骤为____ 、校验和___解释执行__ 。
7、如果一个java applet源程序文件只定义有一个类,该类的类名为myapplet,则类myapplet必须是类的子类并且存储该源程序文件的文件名为。
8、如果一个java applet程序文件中定义有3个类,则使用sun 公司的jdk编译器编译该源程序文件将产生3一个文件名与类名相同而扩展名为__class ______________ 的字节码文件。
11、编写一个简单的java应用程序,该程序在命令行窗口输出两行文字:“你好,很高兴学习java”和“we are students”。
解答:class myfirstjava{public static void main(string args[]){system・out.println(“你好,很高兴学习java”);system.out.println(“we are students”);}}第2章java基本的程序设计结构2.7练习思考题1、a, b, d2、C3、a4、b5、d6、d, f7、b8、d9、d10、a11、D12、a 13、B 14、c15、d16、a17、在java的基本数据类型中,char型采用unicode编码方案,每个unicode码占用字节内存空间,这样,无论是中文字符还是英文字符,都是占用字节内存空间。
18、设x = 2,则表达式( x + + )/3的值是。
19、若x = 5, y = 10,则x y和x = y的逻辑值分别为和。
20、设有数组定义:int myintarray[] = { 10, 20, 30, 40, 50, 60, 70 };则执行以下几个语句后的输出结果是:120。
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毫秒。
在一个正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()); }
}。