java2实用教程(第三版)第七章课后习题答案(耿祥义)

合集下载

Java面向对象程序设计_习题解答(耿祥义)

Java面向对象程序设计_习题解答(耿祥义)

书后习题参考答案习题1 (2)习题2 (3)习题3 (4)习题4 (10)习题5 (11)习题6 (14)习题7 (15)习题9 (16)习题12 (20)习题13 (25)习题14 (27)习题15 (28)习题16 (31)习题17 (39)1.James Gosling2.(1)使用一个文本编辑器编写源文件。

(2)使用Java编译器(javac.exe)编译Java源程序,得到字节码文件。

命令:javac –d . 文件名称.java(3)使用J ava解释器(java.exe)运行Java程序。

命令:java 包名.类名3.Java的源文件是由若干个书写形式互相独立的类、接口、枚举等组成。

应用程序中可以没有public类,若有的话至多可以有一个public类。

4.新建JA V A_HOME系统环境变量,指向安装目录在系统环境变量path中增加内容:%JAVA_HOME%\bin;新建系统环境变量classpath并填入三项:.; %JAVA_HOME%\lib\dt.jar; %JAVA_HOME%\lib\tools.jar 5. B6.Java源文件的扩展名是.java。

Java字节码的扩展名是.class。

7. D8.(1)Speak.java(2)生成两个字节码文件,这些字节码文件的名字Speak.class和Xiti8.class (3)java Xiti8(4)执行java Speak的错误提示Exception in thread "main" ng.NoSuchMethodError: main执行java xiti8得到的错误提示Exception in thread "main" ng.NoClassDefFoundError: xiti8 (wrong name: Xiti8)执行java Xiti8.class得到的错误提示Exception in thread "main" ng.NoClassDefFoundError: Xiti8/class执行java Xiti8得到的输出结果I'm glad to meet you9.属于操作题,解答略。

Java面向对象程序设计_习题解答(耿祥义)

Java面向对象程序设计_习题解答(耿祥义)

书后习题参考答案习题1 2习题2 3习题3 4习题4 10习题5 11习题6 14习题7 15习题9 16习题12 20习题13 25习题14 27习题15 28习题16 31习题17 39习题11.James Gosling2.(1)使用一个文本编辑器编写源文件。

(2)使用Java编译器(javac.exe)编译Java源程序,得到字节码文件。

命令:javac –d . 文件名称.java(3)使用Java解释器(java.exe)运行Java程序。

命令:java 包名.类名3.Java的源文件是由若干个书写形式互相独立的类、接口、枚举等组成。

应用程序中可以没有public类,若有的话至多可以有一个public类。

4.新建JAVA_HOME系统环境变量,指向安装目录在系统环境变量path中增加内容:%JAVA_HOME%\bin;新建系统环境变量classpath并填入三项:.; %JAVA_HOME%\lib\dt.jar; %JAVA_HOME%\lib\tools.jar5. B6. Java源文件的扩展名是.java。

Java字节码的扩展名是.class。

7. D8.(1)Speak.java(2)生成两个字节码文件,这些字节码文件的名字Speak.class和Xiti8.class(3)java Xiti8(4)执行java Speak的错误提示Exception in thread "main" ng.NoSuchMethodError: main执行java xiti8得到的错误提示Exception in thread "main" ng.NoClassDefFoundError: xiti8 (wrong name: Xiti8)执行java Xiti8.class得到的错误提示Exception in thread "main" ng.NoClassDefFoundError:Xiti8/class执行java Xiti8得到的输出结果I'm glad to meet you9.属于操作题,解答略。

Java2实用教程(第三版)实验指导与习题解答

Java2实用教程(第三版)实验指导与习题解答

Java2实用教程(第三版)实验指导与习题解答Java 2实用教程(第三版)实验指导与习题解答清华大学出版社(编著耿祥义张跃平)实验模版代码及答案建议使用文档结构图(选择Word菜单→视图→文档结构图)1上机实践 1 初识JAVA ................................................................................................................. 4 实验 1 一个简单的应用程序.................................................................................................... 4 实验 2 一个简单的JAVA APPLET程序...................................................................................... 4 实验 3 联合编译 (5)上机实践 2 基本数据类型与控制语句 ........................................................................................ 6 实验1 输出希腊字母表 ............................................................................................................ 6 实验 2 回文数 . (7)实验 3 猜数字游戏.................................................................................................................... 9 上机实践 3 类与对象.................................................................................................................. 10 实验 1 三角形、梯形和圆形的类封装................................................................................... 10 实验2 实例成员与类成员 ...................................................................................................... 13 实验3 使用*****语句与IMPORT语句 ............................................................................ 15 上机实践4 继承与接口.............................................................................................................. 17 实验1 继承..............................................................................................................................17 实验 2 上转型对象.................................................................................................................. 20 实验3接口回调 (22)上机实践 5 字符串、时间与数字.............................................................................................. 24 实验 1 STRING类的常用方法.................................................................................................. 24 实验 2 比较日期的大小 ..........................................................................................................25 实验 3 处理大整数.................................................................................................................. 26 上机实践 6 组件及事件处理...................................................................................................... 27 实验1 算术测试......................................................................................................................27 实验 2 信号灯 (30)实验 3 布局与日历.................................................................................................................. 32 上机实践7 组件及事件处理2 ................................................................................................... 36 实验1 方程求根 . (36)实验 2 字体对话框.................................................................................................................. 39 实验 3 英语单词拼写训8 多线程 (46)实验 1 汉字打字练习 .............................................................................................................. 46 实验2 旋转的行星.................................................................................................................. 48 实验 3 双线程接力.................................................................................................................. 52 上机实践9 输入输出流.............................................................................................................. 55 实验1 学读汉字. (55)实验 2 统计英文单词字 .......................................................................................................... 58 实验2 读取ZIP文件 (62)2上机实践10 JAVA 中的网络编程 ............................................................................................ 63 实验1 读取服务器端文件 (63)实验 2 使用套接字读取服务器端对象................................................................................... 65 实验3 基于UDP的图像传输 ................................................................................................ 68 上机实践11 数据结构................................................................................................................ 72 实验 1 扫雷小游戏.................................................................................................................. 72 实验 2 排序与查验 3 使用*****排序 ...................................................................................................... 78 上机实践12 JAVA SWING .......................................................................................................80 实验 1 *****DPANE分层窗格 ............................................................................................ 80 实验2 使用表格显示日历 (81)实验 3 多文档界面(MDI) (84)3上机实践1 初识Java实验1 一个简单的应用程序1.答案:【代码1】:System.out.println(\你好,很高兴学习Java\【代码2】:System.out.println(\2.模板代码Hello.javapublic class Hello {public static void main (String args[ ]) {【代码1】//命令行窗口输出\你好,很高兴学习Java\ A a=new A(); a.fA(); } } class A {void fA() {【代码2】//命令行窗口输出\ } }实验2 一个简单的Java Applet程序1.答案:【代码1】:g.drawString(\这是一个Java Applet 程序\【代码2】:g.drawString(\我改变了字体\2.模板代码FirstApplet.javaimport java.applet.*;4import java.awt.*;public class FirstApplet extends Applet {public void paint(Graphics g) {g.setColor(Color.blue);【代码1】//在Java Applet中绘制一行文字:“这是一个Java Applet 程序” g.setColor(Color.red);g.setFont(new Font(\宋体\【代码2】//在Java Applet中绘制一行文字:“我改变了字体” } }实验3 联合编译1.答案:【代码1】:System.out.println(\你好,只需编译我\【代码2】:System.out.println(\【代码3】:System.out.println(\【代码4】:System.out.println(\ C\2.模板代码模板1:Hello.javapublic class MainClass {public static void main (String args[ ]) {【代码1】//命令行窗口输出\你好,只需编译我\ A a=new A();a.fA(); B b=new B();b.fB(); } }模板2 :A.javapublic class A {void fA() {【代码2】//命令行窗口输出\ } }5。

JAVA实用教程(第三版)课后习题及答案

JAVA实用教程(第三版)课后习题及答案
{returna;}}public classB
{
void g()
{
A a=new A(); a.weight=23f; a.f(3,4);
}}
答:a.weight=23f;错
1.编写一个类,该类创建的对象可以计算等差数列的和。解:classDengCha{
int start,d; DengCha(){
Case 4: System.out.printf(“%c”,’d’); Break;
}
}
输出:a,b, b,c,d,d
9.下列System.out.printf语句输出的结果是什么?
Char a[]={‘a’,’b’,’c’,’d’,’e’}; For(i=0; i<=a.length/2; i++)
答:不,只加载本程序用到的类到内存中,因为java程序是动态加载, 字节码类文件。
16.有哪几种访问权限修饰符?说出一种的作用。答:访问权限修饰符有public,private,protected.
Private作用是只允许本类的对象访问。
17.怎样反编译一个类?
答:使用SDK提供的反编译器javap.exe文件可以实现将字节码文件反编译为源码文件。可查看源码中public方法和public成员变量的名字。如加入参数-private则可列出其全部的成员方法和成员变量。
9.请阐述为什么类方法不能调用实例方法?
答:对于类方法在该类加到内存时就分配了相应的入口地址,所以即使该类未创建对象,也可以通过类名调用类方法。而这时在类对象创建之前,实例方法还没有入口地址。还不知道一个方法从何处开始执
行,当然不能调用。
10.请阐述,为什么类方法中不能操作实例成员变量?

java面向对象程序设计课后习题答案耿祥义张跃平主编清华大学出版社

java面向对象程序设计课后习题答案耿祥义张跃平主编清华大学出版社

习题解答习题11.James Gosling2.需3个步骤:1)用文本编辑器编写源文件.2)使用javac编译源文件,得到字节码文件.3)使用解释器运行程序。

3.由类构成。

不就是必须得。

4. path=D:\jdk\bin;set classpath=D:\jdk\jre\lib\rt、jar;、;5、B6、Java源文件得扩展名就是、java,Java字节码得扩展名就是、class.7。

D。

8. A:Speak、java.B:两个字节码文件,Speak、class与Xiti8、class。

C:java Xiti8。

D:执行java Speak得错误提示Exception in thread "main" java、lang、NoSuchMethodError:main执行javaxiti8得到得错误提示Exception in thread "main"java、lang、NoClassDefFoundError:xiti8(wrong name:Xiti8)执行javaXiti8、class得到得错误提示Exception in thread"main" java、lang、NoClassDefFoundErr or:Xiti8/class执行java Xiti8得到得输出结果I’m glad to meet you(4)9。

属于操作题,解答略。

习题21. D2.【代码1】【代码2】错误//【代码3】更正为float z=6.89F;3。

float型常量后面必须要有后缀“f”或“F”。

对于double常量,后面可以有后缀“d”或“D”,但允许省略该后缀。

4.public class Xiti4{public static void main (String args[ ]){char ch1='您’,ch2='我’,ch3=’她’;System、out、println(”\”"+ch1+"\"得位置:"+(int)ch1);System、out、println(”\”"+ch2+"\”得位置:"+(int)ch2);System、out、println(”\""+ch3+”\"得位置:"+(int)ch3);}}5.数组名字、length6.数组名字、length7.【代码1】A,65【代码2】-127【代码3】123456、783,123456、783128。

java2实用教程课后习题答案(第三版编程题)

java2实用教程课后习题答案(第三版编程题)

3. 编写应用程序,求1!+2!+…+10!。

答:class Fact{public static void main(String args[]){int fact,sum=0;for(int i=1;i<=10;i++){fact=1;for(int j=1;j<=i;j++)fact*=j;sum+=fact;}System.out.println("1到10的阶乘之和是:"+sum);}}4. 编写一个应用程序,求100以内的全部素数。

答:class Primes{ public static void main(String args[]){ int w=1;for(int i=2;i<=100;i++){ for(int j=2;j<i;j++){ w=i%j;if(w==0)break;}if(w!=0)System.out.println(i+"是素数");}}}5. 分别用do―while和for循环计算1+1/2!+1/3!+1/4!+…的前20项和。

答: ①for循环class Sum{public static void main(String args[]){int fact;double sum=0;for(int i=1;i<=20;i++){fact=1;for(int j=1;j<=i;j++)fact*=j;sum+=1.0/fact;}System.out.println(sum);}}②do―while循环class Sum{public static void main(String args[]){int i=1;int fact;double sum=0;do{fact=1;int j=0;while(++j<=i)fact*=j;sum+=1.0/fact;}while(++i<=20);System.out.println(sum);}}6. 一个数如果恰好等于它的因子之和,这个数就称为“完数”。

Java2实用教程习题答案__第三版__清华大学出版社

Java2实用教程习题答案__第三版__清华大学出版社

Java2实用教程(第三版)课后习题参考答案第1章 Java入门1. 开发与运行Java程序需要经过哪些主要步骤和过程?答:(1)编写Java源文件:使用文本编辑器(Edit或记事本),拓展名为.java (2)编译Java源文件:使用Java编译器(javac.exe)。

得到字节码文件*.class (3)运行Java程序:Java应用程序使用Java解释器(java.exe)执行字节码文件;Java小应用程序使用支持Java标准的浏览器来执行。

2. 怎样区分应用程序和小应用程序?应用程序的主类或小应用程序的主类必须用public修饰吗?答:①应用程序必须有main方法,这个方法是程序执行的入口。

小应用程序没有main方法。

②应用程序的主类不一定用public修饰;小应用程序的主类必须用public修饰。

3. Java程序是由什么组成的?一个程序中必须要有public类吗?Java源文件的命名规则是怎样的?答:①Java程序由类组成。

②应用程序可以没有public类;小应用程序一定有一个类是public类(主类)。

③应用程序:如果只有一个类,源文件名与该类的类名相同,拓展名为.java;有多个类时,如果有public类(最多一个),源文件名与public类的类名相同,拓展名是.java;没有public类,源文件名与任何一个类的类名相同即可,拓展名为.java。

小应用程序:源文件名与主类的类名相同,拓展名是.java。

4. 在运行小程序的HTML文件中可以使用codebase属性指定小程序的字节码所驻留的目录。

如果不使用codebase属性,小程序的字节码文件必须和运行它的HTML文件在同一目录中。

编写一个小程序并将小程序的字节码存放在某个目录中,比如C:\5000;把运行该小程序的HTML文件(注意其中的codebase属性): <applet code=你的小程序的字节码 width=200 height=300 codebase=C:\5000> </applet>存放在另一个目录中。

耿祥义张跃平java大学实用教程-编程题答案.(DOC)

耿祥义张跃平java大学实用教程-编程题答案.(DOC)

习题解答第一章作业题1.public class Hello{public static void main (String args[ ]){System.out.pintln(“早上好,good Morning”);}}2.import java.applet.*;import java.awt.*;public class Boy extends Applet {public void paint(Graphics g) {g.setColor(Color.blue);g.drawString("你好,hello",12,30);}}第二章作业题1.public class ZuoYe2_1{public static void main (String args[ ]){char c='а';System.out.println("字母"+c+"在unicode表中的顺序位置:"+(int)c);System.out.println("字母表:");while(c<='я'){System.out.print(" "+c);c=(char)(c+1);}}}2.import java.util.*;public class ZuoYe2_2{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);long chengji=1;int m=0;while(reader.hasNextInt()){int x=reader.nextInt();m=m+1;chengji=chengji*x;}System.out.println(m+"个数的乘积为"+chengji); }}第三章作业题1.import java.util.*;public class ZuoYe3_1{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);double y=0,x=0;x=reader.nextDouble();if(x<0)y=-1+2*x;else if(x==0)y=-1;else if(x>0)y=-1+3*x;System.out.println(y);}}2.public class ZuoYe3_2{public static void main(String args[]){int sum=0,m=3,n=7,a=1;while(a<=1000){if(a%m==0&&a%n==0)sum=sum+a;a++;}System.out.println("sum="+sum);}}3.public class ZuoYe3_3{public static void main(String args[]){long sum=0,a=8,item=a,n=10,i=1;for(i=1;i<=n;i++){ sum=sum+item;item=item*10+a;}System.out.println(sum);}}4.public class ZuoYe3_4{public static void main(String args[]){double sum=0,a=1,b=1,fuhao=1,item=a/b; int i=1;while(i<=1000){sum=sum+fuhao*item;i++;fuhao=fuhao*(-1);b=b+2;item=a/b;}System.out.println("sum="+sum);}}5.public class ZuoYe3_5{public static void main(String args[]) {double sum=0,a=1;int i=1;while(i<=20){if(i>=10)sum=sum+a;i++;a=a*i;}System.out.println("sum="+sum);}}8.第四章作业题1.class DengCha{int start,d;DengCha(){}DengCha(int start,int d){this.start=start;this.d=d;}void setStart(int s){start=s;}void setD(int d){this.d=d;}int getSum(int n){int sum=0,i=1;while(i<=n){sum=sum+start;start=start+d;i++;}return sum;}}public class ZuoYe4_1{public static void main (String args[ ]) {DengCha shulie=new DengCha(2,3);System.out.println(shulie.getSum(100)); shulie.setStart(10);shulie.setD(5);System.out.println(shulie.getSum(9)); }}2.class Letter{public void printLetter(){for(char c='a';c<='z';c++)System.out.print(" "+c);}}public class ZuoYe4_2{public static void main (String args[ ]) {Letter p=new Letter();p.printLetter();}}3.class SquareEquation{double a,b;static double c;double root1,root2;boolean boo;public SquareEquation(double a,double b,double c){this.a=a;this.b=b;SquareEquation.c=c;if(a!=0){boo=true;}else{boo=false;}}public void getRoots(){if(boo){System.out.println("是一元2次方程");double disk=b*b-4*a*c;if(disk>=0){root1=(-b+Math.sqrt(disk))/(2*a);root2=(-b-Math.sqrt(disk))/(2*a);System.out.printf("方程的根:%f,%f\n",root1,root2); }else{System.out.printf("方程没有实根\n");}}else{System.out.println("不是一元2次方程");}}public void setCoefficient(double a,double b,double c){this.a=a;this.b=b;SquareEquation.c=c;if(a!=0){boo=true;}else{boo=false;}}}public class ZuoYe4_3{public static void main(String args[ ]){SquareEquation equation1=new SquareEquation(4,5,1); SquareEquation equation2=new SquareEquation(3,5,-7); equation1.getRoots();equation2.getRoots();}}4.import java.util.Scanner;class A{int f(int m,int n){if(m*n<0){ System.out.println("有负数,程序退出");System.exit(0);}if(m<n){ int temp=m;m=n;n=temp;}int a=m,b=n;int r=m%n;while(r!=0){ m=n;n=r;r=m%n;}return n;}}class B{A a;B(){a=new A();}int g(int m,int n){int temp=a.f(m,n);return m*n/temp;}}public class ZuoYe4_4{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);System.out.println("输入2个正整数,程序计算出它们的最大公约数和最小公倍数");System.out.print("输入第一个整数:");int m=reader.nextInt();System.out.print("输入第二个整数:");int n=reader.nextInt();A a=new A();B b=new B();System.out.println(m+"和"+n+"的最大公约数是"+a.f(m,n));System.out.println(m+"和"+n+"的最小公倍数是"+b.g(m,n));}}5.import java.applet.Applet;import java.awt.*;public class Example4_10 extends Applet{Button redbutton;public void init(){redbutton=new Button("我是一个红色的按钮");redbutton.setBackground(Color.red);redbutton.setForeground(Color.white);add(redbutton);}}第五章作业题1.import java.util.Scanner;class A{public int f(int m,int n){if(m<n){int temp=m;m=n;n=temp;}int r=m%n;while(r!=0){m=n;n=r;r=m%n;}return n;}}class B extends A{public int f(int m,int n){int division=super.f(m,n);return (m*n)/division;}}public class ZuoYe5_1{public static void main (String args[ ]) {A a=new A();B b=new B();Scanner reader=new Scanner(System.in);System.out.println("输入2个整数,程序计算出它们的最大公约数和最小公倍数");System.out.print("输入第一个整数:");int m=reader.nextInt();System.out.print("输入第二个整数:");int n=reader.nextInt();if(m*n<0){ System.out.println("有负数,程序退出");System.exit(0);}System.out.printf("%d和%d的最大公约数是%d\n",m,n,a.f(m,n));System.out.printf("%d和%d的最小公倍数是%d\n",m,n,b.f(m,n));}}2.abstract class A{public abstract void f(int x);public abstract void g(int x,int y);public abstract double h(double x);}class A1 extends A{public void f(int x){System.out.println(x);}public void g(int x,int y){int z=x+y;System.out.println(z);}public double h(double x){return x*x;}}class A2 extends A{public void f(int x){System.out.println("Hello:"+x);}public void g(int x,int y){int z=x-y;System.out.println(z);}public double h(double x){return Math.sqrt(x);}}class A3 extends A{public void f(int x){System.out.println("你好:"+x);}public void g(int x,int y){double z=(double)x/y;System.out.println(z);}public double h(double x){return 1/x;}}public class ZuoYe5_2{public static void main(String args[ ]){ A a=new A1();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A2();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A3();a.f(10);a.g(12,20);System.out.println(a.h(100));}}3.interface A{public abstract void f(int x);public abstract void g(int x,int y); public abstract double h(double x); }class A1 implements A{public void f(int x){System.out.println(x);}public void g(int x,int y){int z=x+y;System.out.println(z);}public double h(double x){return x*x;}}class A2 implements A{public void f(int x){System.out.println("Hello:"+x); }public void g(int x,int y){int z=x-y;System.out.println(z);}public double h(double x){return Math.sqrt(x);}}class A3 implements A{public void f(int x){System.out.println("你好:"+x); }public void g(int x,int y){double z=(double)x/y;System.out.println(z);}public double h(double x){return 1/x;}}public class ZuoYe5_3{public static void main(String args[ ]){ A a=new A1();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A2();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A3();a.f(10);a.g(12,20);System.out.println(a.h(100));}}4.class Cubic{ double getCubic(int n){ return 0;}}abstract class Sqrt{ public abstract double getSqrt(int x);}class A{ void f(Cubic cubic){ double result=cubic.getCubic(3);System.out.println(result);}}public class ZuoYe5_4{ public static void main(String args[]){ A a=new A();a.f(new Cubic(){ double getCubic(int n){ return n*n*n;}});Sqrt ss=new Sqrt(){ public double getSqrt(int x){ return Math.sqrt(x);}};double m=ss.getSqrt(5);System.out.println(m);}}5.class IntegerException extends Exception{ String message;IntegerException(int m){ message="年龄"+m+"不合理";}public String toString(){ return message;}}class People{ private int age=1;public void setAge(int age) throws IntegerException{if(age>=160||age<=0)throw new IntegerException(age); //方法抛出异常,导致方法结束 elsethis.age=age;}public int getAge(){ System.out.println("年龄"+age+"合理");return age;}}public class ZuoYe6_5{ public static void main(String args[]){ People wang=new People(),zhang=new People();try { wang.setAge(189);System.out.println(wang.getAge());}catch(IntegerException e){ System.out.println(e.toString());}try { zhang.setAge(28);System.out.println(zhang.getAge());}catch(IntegerException e){ System.out.println(e.toString());}}}第六章作业题1.import java.util.regex.*;import java.util.*;public class ZuoYe6_1{public static void main(String args[ ]){Scanner reader=new Scanner(System.in);String s1=reader.nextLine();Pattern p;Matcher m;p=pile("[24680]A[13579]{2}");m=p.matcher(s1);while(m.find()){String str=m.group();System.out.print("从"+m.start()+"到"+m.end()+"匹配模式子序列:"); System.out.println(str);}}}2.import java.util.regex.*;import java.util.*;public class ZuoYe4_1{public static void main(String args[ ]){Scanner reader=new Scanner(System.in);String s1=reader.nextLine();Pattern p;Matcher m;p=pile("\\d+");m=p.matcher(s1);while(m.find()){String str=m.group();System.out.print(str);}}}第七章作业题1.import java.util.*;public class ZuoYe7_2{ public static void main(String args[]){int year,month;try{year=Integer.parseInt(args[0]);month=Integer.parseInt(args[1])+1;}catch(NumberFormatException e){year=2004;month=1;}System.out.println(" 日一二三四五六");Calendar 日历=Calendar.getInstance();日历.set(year,month,1);int 星期几=日历.get(Calendar.DAY_OF_WEEK)-1;String a[]=new String[星期几+31];for(int i=0;i<星期几;i++){ a[i]="**";}for(int i=星期几,n=1;i<星期几+31;i++){ if(n<=9)a[i]=String.valueOf(n)+" ";elsea[i]=String.valueOf(n) ;n++;}for(int i=0;i<a.length;i++){ if(i%7==0){ System.out.println("");}System.out.print(" "+a[i]);}}}2.class ZuoYe7_2{ public static void main(String args[]){int year1,month1,day1,year2,month2,day2;try{year1=Integer.parseInt(args[0]);month1=Integer.parseInt(args[1]);day1=Integer.parseInt(args[2]);year2=Integer.parseInt(args[3]);month2=Integer.parseInt(args[4]);day2=Integer.parseInt(args[5]);}catch(NumberFormatException e){year1=2009;month1=0;day1=1;year2=2008;month2=0;day2=1;}Calendar calendar=Calendar.getInstance();calendar.set(year1,month1,day1);long timeYear1=calendar.getTimeInMillis();calendar.set(year2,month2,day2);long timeYear2=calendar.getTimeInMillis();long 相隔天数=Math.abs((timeYear1-timeYear2)/(1000*60*60*24));System.out.println(""+year1+"年"+month1+"月"+day1+"日和"+year2+"年"+month2+"月"+day2+"日相隔"+相隔天数+"天");}}3.import java.math.*;public class ZuoYe4_1{public static void main(String args[]){BigInteger chengji=new BigInteger("1"),ONE=new BigInteger("1"),i=ONE,m=new BigInteger("10");while(pareTo(m)<=0){chengji=chengji.multiply(i);i=i.add(ONE);}System.out.println(chengji);}}4.import java.util.*;public class ZuoYe7_4{public static void main(String args[]){HashSet<Integer> A=new HashSet<Integer>(),B=new HashSet<Integer>(),tempSet=new HashSet<Integer>();A.add(new Integer(1));A.add(new Integer(2));A.add(new Integer(3));A.add(new Integer(4));B.add(new Integer(1));B.add(new Integer(3));B.add(new Integer(7));B.add(new Integer(9));B.add(new Integer(11));tempSet=(HashSet<Integer>)A.clone();tempSet.retainAll(B);System.out.println("交:");Iterator<Integer> iter=tempSet.iterator(); while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue()); }tempSet=(HashSet<Integer>)A.clone();tempSet.addAll(B);iter=tempSet.iterator();System.out.println("并:");while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue()); }tempSet=(HashSet<Integer>)A.clone();tempSet.removeAll(B);System.out.println("差:");iter=tempSet.iterator();while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue()); }}}5.import java.util.*;class MyKey implements Comparable{double number=0;MyKey(double number){this.number=number;}public int compareTo(Object b){MyKey st=(MyKey)b;if((this.number-st.number)==0){return -1;}else{return (int)((this.number-st.number)*1000);}}}class 硬盘{int size;double price;硬盘(int n, double p){size=n;price=p;}}public class ZuoYe4_1{public static void main(String args[ ]){int [] size={10,3,7,12,10,22,100,4,6,2};double [] price={1.2,9.56,2.4,9.3,16.77,12.66,7.4,5.5,5.6,8.9,1.9};硬盘 [] s=new 硬盘[10];for(int i=0;i<s.length;i++)s[i]=new 硬盘(size[i],price[i]);TreeMap<MyKey,硬盘> treemap=new TreeMap<MyKey,硬盘>();for(int i=0;i<s.length;i++)treemap.put(new MyKey(s[i].size),s[i]);int number=treemap.size();System.out.println("树映射中有"+number+"个对象:");Collection<硬盘> collection=treemap.values();Iterator<硬盘> iter=collection.iterator();while(iter.hasNext()){硬盘 te=iter.next();System.out.println(te.size+","+te.price);}treemap.clear();for(int i=0;i<s.length;i++)treemap.put(new MyKey(s[i].price),s[i]);number=treemap.size();System.out.println("树映射中有"+number+"个对象:"); collection=treemap.values();iter=collection.iterator();while(iter.hasNext()){硬盘 te=iter.next();System.out.println(te.size+","+te.price);}}}第八章作业题1.属于操作题目,省略2.参见例子8-23.参见例子8-34.参见例子8-10第九章作业题1.import java.io.*;import java.awt.*;import java.awt.event.*;public class ZuoYe9_1{ public static void main(String args[]){ int b;byte tom[]=new byte[25];try{ File f=new File("Example.java");FileInputStream in=new FileInputStream(f);while((b=in.read(tom,0,25))!=-1){ String s=new String (tom,0,b);System.out.print(s);}in.close();}catch(IOException e){ System.out.println("File read Error"+e);}}}2.import java.io.*;import java.util.*;public class ZuoYe9_2{public static void main(String args[]){Scanner reader=new Scanner(System.in);int b;try{FileOutputStream writefile=new FileOutputStream("line.txt"); int line=1,n=10;System.out.println("输入"+n+"行文本,并存入磁盘:");while(line<=n){String s=reader.nextLine();byte buffer[]=s.getBytes();writefile.write(buffer,0,buffer.length);line++;}writefile.close();}catch(IOException e){System.out.println("Error "+e);}}}3.import java.io.*;public class ZuoYe9_3{public static void main(String args[ ]){int n=-1;CharArrayWriter out=new CharArrayWriter();for(char c='а';c<='я';c++){out.write(c);}CharArrayReader in=new CharArrayReader(out.toCharArray()); try{ while((n=in.read())!=-1){if(n%2==0){System.out.printf("\n");}System.out.printf("\t位置%d,字符\'%c\'",n,(char)n); }}catch(IOException e){}}}4.import java.io.*;import java.util.*;public class ZuoYe9_4{public static void main(String args[]){try{FileOutputStream fos=new FileOutputStream("jerry.dat"); DataOutputStream out_data=new DataOutputStream(fos);Scanner reader=new Scanner(System.in);for(int i=1;i<=10;i++){int x=reader.nextInt();out_data.writeInt(x);}out_data.close();}catch(IOException e){}try{FileInputStream fis=new FileInputStream("jerry.dat"); DataInputStream in_data=new DataInputStream(fis);for(int i=1;i<=10;i++){int m=in_data.readInt();System.out.print(" "+m);}in_data.close();}catch(IOException e){}}}5.import java.io.*;import java.util.*;class Student implements Serializable{String name ;int number;Student(String name,int number){=name;this.number=number;}}public class ZuoYe9_5{public static void main(String args[]){List<Student> list=new LinkedList<Student>();List<Student> cloneList=null;for(int k=1;k<=12;k++)list.add(new Student("I am "+k,k));try{ FileOutputStream fileOut=new FileOutputStream("a.txt");ObjectOutputStream objectOut=new ObjectOutputStream(fileOut);objectOut.writeObject(list);FileInputStream fileIn=new FileInputStream("a.txt");ObjectInputStream objectIn=new ObjectInputStream(fileIn);cloneList=(List)objectIn.readObject();}catch(Exception event){System.out.println(event);}Iterator iter=cloneList.iterator();while(iter.hasNext()){Student te=(Student)iter.next();System.out.println(te.number+","+);}}}6.import java.io.*;public class ZuoYe9_6{ public static void main(String args[]){File f=new File("Xiti12_6.java");try{ RandomAccessFile random=new RandomAccessFile(f,"rw");random.seek(0);long m=random.length();while(m>=0){ m=m-1;random.seek(m);int c=random.readByte();if(c<=255&&c>=0){ System.out.print((char)c);}else{ m=m-1; //一个汉字占2个字节 random.seek(m);byte cc[]=new byte[2];random.readFully(cc);System.out.print(new String(cc));}}random.close();}catch(IOException ee){}}}5.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_5{ public static void main(String args[]){ ComputerFrame fr=new ComputerFrame();fr.setTitle("计算");}}class ComputerFrame extends JFrame implements ActionListener { JTextField text1,text2,text3;JButton button1,button2,button3,button4;JLabel label;public ComputerFrame(){setLayout(new FlowLayout());text1=new JTextField(10);text2=new JTextField(10);text3=new JTextField(10);label=new JLabel(" ",JLabel.CENTER);label.setBackground(Color.green);add(text1);add(label);add(text2);add(text3);button1=new JButton("加");button2=new JButton("减");button3=new JButton("乘");button4=new JButton("除");add(button1);add(button2);add(button3);add(button4);button1.addActionListener(this);button2.addActionListener(this);button3.addActionListener(this);button4.addActionListener(this);setSize(400,320);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); validate();}public void actionPerformed(ActionEvent e){ double n;if(e.getSource()==button1){ double n1,n2;try{ n1=Double.parseDouble(text1.getText()); n2=Double.parseDouble(text2.getText()); n=n1+n2;text3.setText(String.valueOf(n));label.setText("+");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button2){ double n1,n2;try{ n1=Double.parseDouble(text1.getText()); n2=Double.parseDouble(text2.getText()); n=n1-n2;text3.setText(String.valueOf(n));label.setText("-");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button3){double n1,n2;try{ n1=Double.parseDouble(text1.getText()); n2=Double.parseDouble(text2.getText()); n=n1*n2;text3.setText(String.valueOf(n));label.setText("*");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button4){double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1/n2;text3.setText(String.valueOf(n));label.setText("/");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}validate();}}6.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_6{ public static void main(String args[]){ new WindowPanel();}}class Mypanel extends JPanel implements ActionListener { JButton button;JTextField text;Mypanel(){ button=new JButton(" ");text=new JTextField(12);add(button);add(text);button.addActionListener(this);}public void actionPerformed(ActionEvent e){ String name=text.getText();if(name.length()>0)button.setText(name);validate();}}class WindowPanel extends JFrame{ Mypanel panel1,panel2;WindowPanel(){ panel1=new Mypanel();panel2=new Mypanel();panel1.setBackground(Color.red);panel2.setBackground(Color.blue);add(panel1,BorderLayout.SOUTH);add(panel2,BorderLayout.NORTH);setSize(300,320);setVisible(true);validate();setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}7.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_7{ public static void main(String args[]){ new WindowColor();}}class WindowColor extends JFrame{ JButton button;JTextField text;JComboBox list;WindowColor(){ setLayout(new FlowLayout());button=new JButton("hello");button.setBackground(Color.pink);button.setForeground(new Color(12,26,200));text=new JTextField("how are you");text.setBackground(Color.yellow);text.setForeground(new Color(200,26,20));list=new JComboBox();list.addItem("Hello");list.addItem("Java");list.setBackground(Color.cyan);list.setForeground(new Color(100,100,100));add(list);add(button);add(text);setSize(300,320);setVisible(true);validate();setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}8.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_8{ public static void main(String args[]){ MoveFrame f=new MoveFrame();f.setBounds(12,12,300,300);f.setVisible(true);f.setTitle("移动");f.validate();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}class MoveFrame extends JFrame implements ActionListener { JButton controlButton,movedButton;public MoveFrame(){ controlButton=new JButton("单击我运动另一个按钮");controlButton.addActionListener(this);movedButton=new JButton();movedButton.setBackground(new Color(12,200,34));setLayout(null);add(controlButton);add(movedButton);controlButton.setBounds(10,30,180,30);movedButton.setBounds(100,100,20,20);}public void actionPerformed(ActionEvent e){ int x=movedButton.getBounds().x;int y=movedButton.getBounds().y;x=x+5;y=y+1;movedButton.setLocation(x,y);if(x>200){ x=100;y=100;}}}9.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class E{ public static void main(String args[]){ JFrame fr=new JFrame();fr.add(new LP(),BorderLayout.CENTER);fr.setVisible(true);fr.setBounds(12,12,300,300);fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);fr.validate();}}class LP extends JLayeredPane implements MouseListener,MouseMotionListener { JButton button[];JTextField text[];int x,y,a,b,x0,y0;LP(){ setLayout(new FlowLayout());button=new JButton[8];for(int k=0;k<button.length;k++){ button[k]=new JButton("用鼠标拖动我");add(button[k]);button[k].addMouseListener(this);button[k].addMouseMotionListener(this);}text=new JTextField[10];for(int k=0;k<text.length;k++){ text[k]=new JTextField("用鼠标拖动我");text[k].addMouseListener(this);add(text[k]);text[k].addMouseMotionListener(this);}addMouseMotionListener(this);}public void mousePressed(MouseEvent e){ Component com=null;com=(Component)e.getSource();setLayer(com,JLayeredPane.DRAG_LAYER);a=com.getBounds().x;b=com.getBounds().y;x0=e.getX(); //获取鼠标在事件源中的位置坐标y0=e.getY();}public void mouseReleased(MouseEvent e){ Component com=null;com=(Component)e.getSource();setLayer(com,JLayeredPane.DEFAULT_LAYER);Component component[]=this.getComponents();for(int k=0;k<component.length;k++){ Rectangle rect1=component[k].getBounds();Rectangle rect2=com.getBounds();if(rect1.intersects(rect2)&&com!=component[k]){ component[k].setVisible(false);//this.remove(component[k]); }}}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mouseClicked(MouseEvent e){}public void mouseMoved(MouseEvent e){}public void mouseDragged(MouseEvent e){ Component com=null;if(e.getSource() instanceof Component){ com=(Component)e.getSource();a=com.getBounds().x;b=com.getBounds().y;x=e.getX(); //获取鼠标在事件源中的位置坐标 y=e.getY();a=a+x;b=b+y;com.setLocation(a-x0,b-y0);}}}10.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class E{ public static void main(String args[]){ JFrame fr=new JFrame();fr.add(new MoveButton(),BorderLayout.CENTER);fr.setVisible(true);fr.setBounds(12,12,300,300);fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);fr.validate();}}class MoveButton extends JLayeredPane implements KeyListener { JButton b[]=new JButton[8];int x,y;MoveButton(){ setLayout(new FlowLayout());for(int i=0;i<8;i++){ b[i]=new JButton(""+i);b[i].addKeyListener(this);。

java2实用教程耿祥义_张跃平编著(3版)习题解答__课后答案

java2实用教程耿祥义_张跃平编著(3版)习题解答__课后答案

java2实用教程耿祥义张跃平编著(3版)习题解答1-17章完整版.doc第一章习题1.需3个步骤:1)用文本编辑器编写源文件2)使用javac编译源文件,得到字节码文件3)应用程序使用解释器运行;小应用程序使用浏览器运行。

2.应用程序必须有一个类含有public static void main(String args[])方法,含有该方法的类称为应用程序的主类。

小应用程序必须有一个类是java.applet.Applet类的子类,该类称做主类。

应用程序中可以没有public类,若有的话可以是应用程序中的任何一个类。

小应用程序的主类必须用public修饰。

3.java的源程序是由若干个书写形式互相独立的类组成的。

小应用程序的主类必须用public修饰。

应用程序中可以没有public类,若有的话可以是应用程序中的任何一个类。

一个java的源程序至多可以有一个public类。

Java源文件的名字可以和其中某个类的名字相同,扩展名是.java,但是,如果源程序中有public类,那么源文件的名字必须和这个public 类的名字相同,扩展名是.java。

4.属于操作,解答略。

第二章习题1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。

标识符由字母、下划线、美元符号和数字组成,并且第一个字符不能是数字字符2.关键字就是Java语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来用。

3.boolean ,char,byte,short,int,long,float,double。

4.b=x;5.数组b的长度为4b[0]=16.属于操作题,解答略。

7.属于操作题,解答略。

8.public class E{ public static void main (String args[ ]) { char cStart='α',cEnd='ω';for(char c=cStart;c<=cEnd;c++){ System.out.print(" "+c);}}}第三章习题1.你爱她2.beep!!3.public class Xiti3_3{ public static void main(String args[]){ double sum=0,a=1;int i=1;while(i<=20){ sum=sum+a;i++;a=a*i;}System.out.println("sum="+sum);}}4.public class Xiti4{ public static void main(String args[]){ int i,j;for(j=2;j<=100;j++){ for(i=2;i<=j/2;i++){ if(j%i==0)break;}if(i>j/2){ System.out.print(" "+j);}}}}5.class Xiti5{ public static void main(String args[]){ double sum=0,a=1,i=1;do { sum=sum+a;i++;a=(1.0/i)*a;}while(i<=20);System.out.println("使用do-while循环计算的sum="+sum);for(sum=0,i=1,a=1;i<=20;i++){ a=a*(1.0/i);sum=sum+a;}System.out.println("使用for循环计算的sum="+sum);}}6.class Xiti6{ public static void main(String args[]){ int sum=0,i,j;for(i=1;i<=1000;i++){ for(j=1,sum=0;j<i;j++){ if(i%j==0)sum=sum+j;}if(sum==i)System.out.println("完数:"+i);}}}7.public class E Xiti7{ public static void main(String args[]){ int m=8,item=m,i=1;long sum=0;while(i<=10){ sum=sum+item;i++;item=item*10+m;}System.out.println(sum);for(i=1,sum=0,item=m;i<=10;i++){ sum=sum+item;item=item*10+m;}System.out.println(sum);}}8.public class E{ public static void main(String args[]){ int n=1;long sum=0;while(true){ sum=sum+n;n++;if(sum>=8888)break;}System.out.println("满足条件的最大整数:"+(n-1));}}第四章习题1.用该类创建对象时。

java大学实用教程(第三版)课后答案

java大学实用教程(第三版)课后答案

习题解答第一章作业题1.public class Hello{public static void main (String args[ ]){System.out.pintln(“早上好,good Morning”);}}2.import java.applet.*;import java.awt.*;public class Boy extends Applet {public void paint(Graphics g) {g.setColor(Color.blue);g.drawString("你好,hello",12,30);}}第二章作业题1.public class ZuoYe2_1{public static void main (String args[ ]){char c='а';System.out.println("字母"+c+"在unicode表中的顺序位置:"+(int)c);System.out.println("字母表:");while(c<='я'){System.out.print(" "+c);c=(char)(c+1);}}}2.import java.util.*;public class ZuoYe2_2{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);long chengji=1;int m=0;while(reader.hasNextInt()){int x=reader.nextInt();m=m+1;chengji=chengji*x;}System.out.println(m+"个数的乘积为"+chengji);}}第三章作业题1.import java.util.*;public class ZuoYe3_1{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);double y=0,x=0;x=reader.nextDouble();if(x<0)y=-1+2*x;else if(x==0)y=-1;else if(x>0)y=-1+3*x;System.out.println(y);}}2.public class ZuoYe3_2{public static void main(String args[]){int sum=0,m=3,n=7,a=1;while(a<=1000){if(a%m==0&&a%n==0)sum=sum+a;a++;}System.out.println("sum="+sum);}}3.public class ZuoYe3_3{public static void main(String args[]){long sum=0,a=8,item=a,n=10,i=1;for(i=1;i<=n;i++){ sum=sum+item;item=item*10+a;}System.out.println(sum);}}4.public class ZuoYe3_4{public static void main(String args[]){double sum=0,a=1,b=1,fuhao=1,item=a/b;int i=1;while(i<=1000){sum=sum+fuhao*item;i++;fuhao=fuhao*(-1);b=b+2;item=a/b;}System.out.println("sum="+sum);}}5.public class ZuoYe3_5{public static void main(String args[]){double sum=0,a=1;int i=1;while(i<=20){if(i>=10)sum=sum+a;i++;a=a*i;}System.out.println("sum="+sum);}}8.第四章作业题1.class DengCha{int start,d;DengCha(){}DengCha(int start,int d){this.start=start;this.d=d;}void setStart(int s){start=s;}void setD(int d){this.d=d;}int getSum(int n){int sum=0,i=1;while(i<=n){sum=sum+start;start=start+d;i++;}return sum;}}public class ZuoYe4_1{public static void main (String args[ ]){DengCha shulie=new DengCha(2,3);System.out.println(shulie.getSum(100));shulie.setStart(10);shulie.setD(5);System.out.println(shulie.getSum(9)); }}2.class Letter{public void printLetter(){for(char c='a';c<='z';c++)System.out.print(" "+c);}}public class ZuoYe4_2{public static void main (String args[ ]){Letter p=new Letter();p.printLetter();}}3.class SquareEquation{double a,b;static double c;double root1,root2;boolean boo;public SquareEquation(double a,double b,double c){this.a=a;this.b=b;SquareEquation.c=c;if(a!=0){boo=true;}else{boo=false;}}public void getRoots(){if(boo){System.out.println("是一元2次方程");double disk=b*b-4*a*c;if(disk>=0){root1=(-b+Math.sqrt(disk))/(2*a);root2=(-b-Math.sqrt(disk))/(2*a);System.out.printf("方程的根:%f,%f\n",root1,root2);}else{System.out.printf("方程没有实根\n");}}else{System.out.println("不是一元2次方程");}}public void setCoefficient(double a,double b,double c){ this.a=a;this.b=b;SquareEquation.c=c;if(a!=0){boo=true;}else{boo=false;}}}public class ZuoYe4_3{public static void main(String args[ ]){SquareEquation equation1=new SquareEquation(4,5,1);SquareEquation equation2=new SquareEquation(3,5,-7);equation1.getRoots();equation2.getRoots();}}4.import java.util.Scanner;class A{int f(int m,int n){if(m*n<0){ System.out.println("有负数,程序退出");System.exit(0);}if(m<n){ int temp=m;m=n;n=temp;}int a=m,b=n;int r=m%n;while(r!=0){ m=n;n=r;r=m%n;}return n;}}class B{A a;B(){a=new A();}int g(int m,int n){int temp=a.f(m,n);return m*n/temp;}}public class ZuoYe4_4{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);System.out.println("输入2个正整数,程序计算出它们的最大公约数和最小公倍数");System.out.print("输入第一个整数:");int m=reader.nextInt();System.out.print("输入第二个整数:");int n=reader.nextInt();A a=new A();B b=new B();System.out.println(m+"和"+n+"的最大公约数是"+a.f(m,n));System.out.println(m+"和"+n+"的最小公倍数是"+b.g(m,n));}}5.import java.applet.Applet;import java.awt.*;public class Example4_10 extends Applet{Button redbutton;public void init(){redbutton=new Button("我是一个红色的按钮");redbutton.setBackground(Color.red);redbutton.setForeground(Color.white);add(redbutton);}}第五章作业题1.import java.util.Scanner;class A{public int f(int m,int n){if(m<n){int temp=m;m=n;n=temp;}int r=m%n;while(r!=0){m=n;n=r;r=m%n;}return n;}}class B extends A{public int f(int m,int n){int division=super.f(m,n);return (m*n)/division;}}public class ZuoYe5_1{public static void main (String args[ ]){A a=new A();B b=new B();Scanner reader=new Scanner(System.in);System.out.println("输入2个整数,程序计算出它们的最大公约数和最小公倍数");System.out.print("输入第一个整数:");int m=reader.nextInt();System.out.print("输入第二个整数:");int n=reader.nextInt();if(m*n<0){ System.out.println("有负数,程序退出");System.exit(0);}System.out.printf("%d和%d的最大公约数是%d\n",m,n,a.f(m,n));System.out.printf("%d和%d的最小公倍数是%d\n",m,n,b.f(m,n));}}2.abstract class A{public abstract void f(int x);public abstract void g(int x,int y);public abstract double h(double x); }class A1 extends A{public void f(int x){System.out.println(x);}public void g(int x,int y){int z=x+y;System.out.println(z);}public double h(double x){return x*x;}}class A2 extends A{public void f(int x){System.out.println("Hello:"+x);}public void g(int x,int y){int z=x-y;System.out.println(z);}public double h(double x){return Math.sqrt(x);}}class A3 extends A{public void f(int x){System.out.println("你好:"+x);}public void g(int x,int y){double z=(double)x/y;System.out.println(z);}public double h(double x){return 1/x;}}public class ZuoYe5_2{public static void main(String args[ ]){A a=new A1();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A2();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A3();a.f(10);a.g(12,20);System.out.println(a.h(100));}}3.interface A{public abstract void f(int x);public abstract void g(int x,int y);public abstract double h(double x); }class A1 implements A{public void f(int x){System.out.println(x);}public void g(int x,int y){int z=x+y;System.out.println(z);}public double h(double x){return x*x;}}class A2 implements A{public void f(int x){System.out.println("Hello:"+x);}public void g(int x,int y){int z=x-y;System.out.println(z);}public double h(double x){return Math.sqrt(x);}}class A3 implements A{public void f(int x){System.out.println("你好:"+x);}public void g(int x,int y){double z=(double)x/y;System.out.println(z);}public double h(double x){return 1/x;}}public class ZuoYe5_3{public static void main(String args[ ]){A a=new A1();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A2();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A3();a.f(10);a.g(12,20);System.out.println(a.h(100));}}4.class Cubic{ double getCubic(int n){ return 0;}}abstract class Sqrt{ public abstract double getSqrt(int x); }class A{ void f(Cubic cubic){ double result=cubic.getCubic(3);System.out.println(result);}}public class ZuoYe5_4{ public static void main(String args[]){ A a=new A();a.f(new Cubic(){ double getCubic(int n){ return n*n*n;}});Sqrt ss=new Sqrt(){ public double getSqrt(int x){ return Math.sqrt(x);}};double m=ss.getSqrt(5);System.out.println(m);}}5.class IntegerException extends Exception{ String message;IntegerException(int m){ message="年龄"+m+"不合理";}public String toString(){ return message;}}class People{ private int age=1;public void setAge(int age) throws IntegerException{if(age>=160||age<=0)throw new IntegerException(age); //方法抛出异常,导致方法结束elsethis.age=age;}public int getAge(){ System.out.println("年龄"+age+"合理");return age;}}public class ZuoYe6_5{ public static void main(String args[]){ People wang=new People(),zhang=new People();try { wang.setAge(189);System.out.println(wang.getAge());}catch(IntegerException e){ System.out.println(e.toString());}try { zhang.setAge(28);System.out.println(zhang.getAge());}catch(IntegerException e){ System.out.println(e.toString());}}}第六章作业题1.import java.util.regex.*;import java.util.*;public class ZuoYe6_1{public static void main(String args[ ]){Scanner reader=new Scanner(System.in);String s1=reader.nextLine();Pattern p;Matcher m;p=pile("[24680]A[13579]{2}");m=p.matcher(s1);while(m.find()){String str=m.group();System.out.print("从"+m.start()+"到"+m.end()+"匹配模式子序列:");System.out.println(str);}}}2.import java.util.regex.*;import java.util.*;public class ZuoYe4_1{public static void main(String args[ ]){Scanner reader=new Scanner(System.in);String s1=reader.nextLine();Pattern p;Matcher m;p=pile("\\d+");m=p.matcher(s1);while(m.find()){String str=m.group();System.out.print(str);}}}第七章作业题1.import java.util.*;public class ZuoYe7_2{ public static void main(String args[]){int year,month;try{year=Integer.parseInt(args[0]);month=Integer.parseInt(args[1])+1;}catch(NumberFormatException e){year=2004;month=1;}System.out.println(" 日一二三四五六");Calendar 日历=Calendar.getInstance();日历.set(year,month,1);int 星期几=日历.get(Calendar.DAY_OF_WEEK)-1;String a[]=new String[星期几+31];for(int i=0;i<星期几;i++){ a[i]="**";}for(int i=星期几,n=1;i<星期几+31;i++){ if(n<=9)a[i]=String.valueOf(n)+" ";elsea[i]=String.valueOf(n) ;n++;}for(int i=0;i<a.length;i++){ if(i%7==0){ System.out.println("");}System.out.print(" "+a[i]);}}}2.class ZuoYe7_2{ public static void main(String args[]){int year1,month1,day1,year2,month2,day2;try{year1=Integer.parseInt(args[0]);month1=Integer.parseInt(args[1]);day1=Integer.parseInt(args[2]);year2=Integer.parseInt(args[3]);month2=Integer.parseInt(args[4]);day2=Integer.parseInt(args[5]);}catch(NumberFormatException e){year1=2009;month1=0;day1=1;year2=2008;month2=0;day2=1;}Calendar calendar=Calendar.getInstance();calendar.set(year1,month1,day1);long timeYear1=calendar.getTimeInMillis();calendar.set(year2,month2,day2);long timeYear2=calendar.getTimeInMillis();long 相隔天数=Math.abs((timeYear1-timeYear2)/(1000*60*60*24));System.out.println(""+year1+"年"+month1+"月"+day1+"日和"+year2+"年"+month2+"月"+day2+"日相隔"+相隔天数+"天");}}3.import java.math.*;public class ZuoYe4_1{public static void main(String args[]){BigInteger chengji=new BigInteger("1"),ONE=new BigInteger("1"),i=ONE,m=new BigInteger("10");while(pareTo(m)<=0){chengji=chengji.multiply(i);i=i.add(ONE);}System.out.println(chengji);}}4.import java.util.*;public class ZuoYe7_4{public static void main(String args[]){HashSet<Integer> A=new HashSet<Integer>(),B=new HashSet<Integer>(),tempSet=new HashSet<Integer>();A.add(new Integer(1));A.add(new Integer(2));A.add(new Integer(3));A.add(new Integer(4));B.add(new Integer(1));B.add(new Integer(3));B.add(new Integer(7));B.add(new Integer(9));B.add(new Integer(11));tempSet=(HashSet<Integer>)A.clone();tempSet.retainAll(B);System.out.println("交:");Iterator<Integer> iter=tempSet.iterator();while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue());}tempSet=(HashSet<Integer>)A.clone();tempSet.addAll(B);iter=tempSet.iterator();System.out.println("并:");while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue());}tempSet=(HashSet<Integer>)A.clone();tempSet.removeAll(B);System.out.println("差:");iter=tempSet.iterator();while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue());}}}5.import java.util.*;class MyKey implements Comparable{double number=0;MyKey(double number){this.number=number;}public int compareTo(Object b){MyKey st=(MyKey)b;if((this.number-st.number)==0){return -1;}else{return (int)((this.number-st.number)*1000);}}}class 硬盘{int size;double price;硬盘(int n, double p){size=n;price=p;}}public class ZuoYe4_1{public static void main(String args[ ]){int [] size={10,3,7,12,10,22,100,4,6,2};double [] price={1.2,9.56,2.4,9.3,16.77,12.66,7.4,5.5,5.6,8.9,1.9};硬盘[] s=new 硬盘[10];for(int i=0;i<s.length;i++)s[i]=new 硬盘(size[i],price[i]);TreeMap<MyKey,硬盘> treemap=new TreeMap<MyKey,硬盘>();for(int i=0;i<s.length;i++)treemap.put(new MyKey(s[i].size),s[i]);int number=treemap.size();System.out.println("树映射中有"+number+"个对象:");Collection<硬盘> collection=treemap.values();Iterator<硬盘> iter=collection.iterator();while(iter.hasNext()){硬盘te=iter.next();System.out.println(te.size+","+te.price);}treemap.clear();for(int i=0;i<s.length;i++)treemap.put(new MyKey(s[i].price),s[i]);number=treemap.size();System.out.println("树映射中有"+number+"个对象:");collection=treemap.values();iter=collection.iterator();while(iter.hasNext()){硬盘te=iter.next();System.out.println(te.size+","+te.price);}}}第八章作业题1.属于操作题目,省略2.参见例子8-23.参见例子8-34. 参见例子8-10第九章作业题1.import java.io.*;import java.awt.*;import java.awt.event.*;public class ZuoYe9_1{ public static void main(String args[]){ int b;byte tom[]=new byte[25];try{ File f=new File("Example.java");FileInputStream in=new FileInputStream(f);while((b=in.read(tom,0,25))!=-1){ String s=new String (tom,0,b);System.out.print(s);}in.close();}catch(IOException e){ System.out.println("File read Error"+e);}}}2.import java.io.*;import java.util.*;public class ZuoYe9_2{public static void main(String args[]){Scanner reader=new Scanner(System.in);int b;try{FileOutputStream writefile=new FileOutputStream("line.txt");int line=1,n=10;System.out.println("输入"+n+"行文本,并存入磁盘:");while(line<=n){String s=reader.nextLine();byte buffer[]=s.getBytes();writefile.write(buffer,0,buffer.length);line++;}writefile.close();}catch(IOException e){System.out.println("Error "+e);}}}3.import java.io.*;public class ZuoYe9_3{public static void main(String args[ ]){int n=-1;CharArrayWriter out=new CharArrayWriter();for(char c='а';c<='я';c++){out.write(c);}CharArrayReader in=new CharArrayReader(out.toCharArray());try{ while((n=in.read())!=-1){if(n%2==0){System.out.printf("\n");}System.out.printf("\t位置%d,字符\'%c\'",n,(char)n);}}catch(IOException e){}}}4.import java.io.*;import java.util.*;public class ZuoYe9_4{public static void main(String args[]){try{FileOutputStream fos=new FileOutputStream("jerry.dat");DataOutputStream out_data=new DataOutputStream(fos);Scanner reader=new Scanner(System.in);for(int i=1;i<=10;i++){int x=reader.nextInt();out_data.writeInt(x);}out_data.close();}catch(IOException e){}try{FileInputStream fis=new FileInputStream("jerry.dat");DataInputStream in_data=new DataInputStream(fis);for(int i=1;i<=10;i++){int m=in_data.readInt();System.out.print(" "+m);}in_data.close();}catch(IOException e){}}}5.import java.io.*;import java.util.*;class Student implements Serializable{String name ;int number;Student(String name,int number){=name;this.number=number;}}public class ZuoYe9_5{public static void main(String args[]){List<Student> list=new LinkedList<Student>();List<Student> cloneList=null;for(int k=1;k<=12;k++)list.add(new Student("I am "+k,k));try{ FileOutputStream fileOut=new FileOutputStream("a.txt");ObjectOutputStream objectOut=new ObjectOutputStream(fileOut);objectOut.writeObject(list);FileInputStream fileIn=new FileInputStream("a.txt");ObjectInputStream objectIn=new ObjectInputStream(fileIn);cloneList=(List)objectIn.readObject();}catch(Exception event){System.out.println(event);}Iterator iter=cloneList.iterator();while(iter.hasNext()){Student te=(Student)iter.next();System.out.println(te.number+","+);}}}import java.io.*;public class ZuoYe9_6{ public static void main(String args[]){File f=new File("Xiti12_6.java");try{ RandomAccessFile random=new RandomAccessFile(f,"rw");random.seek(0);long m=random.length();while(m>=0){ m=m-1;random.seek(m);int c=random.readByte();if(c<=255&&c>=0){ System.out.print((char)c);}else{ m=m-1; //一个汉字占2个字节random.seek(m);byte cc[]=new byte[2];random.readFully(cc);System.out.print(new String(cc));}}random.close();}catch(IOException ee){}}}5.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_5{ public static void main(String args[]){ ComputerFrame fr=new ComputerFrame();fr.setTitle("计算");}class ComputerFrame extends JFrame implements ActionListener { JTextField text1,text2,text3;JButton button1,button2,button3,button4;JLabel label;public ComputerFrame(){setLayout(new FlowLayout());text1=new JTextField(10);text2=new JTextField(10);text3=new JTextField(10);label=new JLabel(" ",JLabel.CENTER);label.setBackground(Color.green);add(text1);add(label);add(text2);add(text3);button1=new JButton("加");button2=new JButton("减");button3=new JButton("乘");button4=new JButton("除");add(button1);add(button2);add(button3);add(button4);button1.addActionListener(this);button2.addActionListener(this);button3.addActionListener(this);button4.addActionListener(this);setSize(400,320);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);validate();}public void actionPerformed(ActionEvent e){ double n;if(e.getSource()==button1){ double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1+n2;text3.setText(String.valueOf(n));label.setText("+");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button2){ double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1-n2;text3.setText(String.valueOf(n));label.setText("-");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button3){double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1*n2;text3.setText(String.valueOf(n));label.setText("*");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button4){double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1/n2;text3.setText(String.valueOf(n));label.setText("/");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}validate();}}6.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_6{ public static void main(String args[]){ new WindowPanel();}}class Mypanel extends JPanel implements ActionListener { JButton button;JTextField text;Mypanel(){ button=new JButton(" ");text=new JTextField(12);add(button);add(text);button.addActionListener(this);}public void actionPerformed(ActionEvent e){ String name=text.getText();if(name.length()>0)button.setText(name);validate();}}class WindowPanel extends JFrame{ Mypanel panel1,panel2;WindowPanel(){ panel1=new Mypanel();panel2=new Mypanel();panel1.setBackground(Color.red);panel2.setBackground(Color.blue);add(panel1,BorderLayout.SOUTH);add(panel2,BorderLayout.NORTH);setSize(300,320);setVisible(true);validate();setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}7.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_7{ public static void main(String args[]){ new WindowColor();}}class WindowColor extends JFrame{ JButton button;JTextField text;JComboBox list;WindowColor(){ setLayout(new FlowLayout());button=new JButton("hello");button.setBackground(Color.pink);button.setForeground(new Color(12,26,200));text=new JTextField("how are you");text.setBackground(Color.yellow);text.setForeground(new Color(200,26,20));list=new JComboBox();list.addItem("Hello");list.addItem("Java");list.setBackground(Color.cyan);list.setForeground(new Color(100,100,100));add(list);add(button);add(text);setSize(300,320);setVisible(true);validate();setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}8.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_8{ public static void main(String args[]){ MoveFrame f=new MoveFrame();f.setBounds(12,12,300,300);f.setVisible(true);f.setTitle("移动");f.validate();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}class MoveFrame extends JFrame implements ActionListener{ JButton controlButton,movedButton;public MoveFrame(){ controlButton=new JButton("单击我运动另一个按钮");controlButton.addActionListener(this);movedButton=new JButton();movedButton.setBackground(new Color(12,200,34));setLayout(null);add(controlButton);add(movedButton);controlButton.setBounds(10,30,180,30);movedButton.setBounds(100,100,20,20);}public void actionPerformed(ActionEvent e){ int x=movedButton.getBounds().x;int y=movedButton.getBounds().y;x=x+5;y=y+1;movedButton.setLocation(x,y);if(x>200){ x=100;y=100;}}}9.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class E{ public static void main(String args[]){ JFrame fr=new JFrame();fr.add(new LP(),BorderLayout.CENTER);fr.setVisible(true);fr.setBounds(12,12,300,300);fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);fr.validate();}}class LP extends JLayeredPane implements MouseListener,MouseMotionListener { JButton button[];JTextField text[];int x,y,a,b,x0,y0;LP(){ setLayout(new FlowLayout());button=new JButton[8];for(int k=0;k<button.length;k++){ button[k]=new JButton("用鼠标拖动我");add(button[k]);button[k].addMouseListener(this);button[k].addMouseMotionListener(this);}text=new JTextField[10];for(int k=0;k<text.length;k++){ text[k]=new JTextField("用鼠标拖动我");text[k].addMouseListener(this);add(text[k]);text[k].addMouseMotionListener(this);}addMouseMotionListener(this);}public void mousePressed(MouseEvent e){ Component com=null;com=(Component)e.getSource();setLayer(com,JLayeredPane.DRAG_LAYER);a=com.getBounds().x;b=com.getBounds().y;x0=e.getX(); //获取鼠标在事件源中的位置坐标y0=e.getY();}public void mouseReleased(MouseEvent e){ Component com=null;com=(Component)e.getSource();setLayer(com,JLayeredPane.DEFAULT_LAYER);Component component[]=this.getComponents();for(int k=0;k<component.length;k++){ Rectangle rect1=component[k].getBounds();Rectangle rect2=com.getBounds();if(rect1.intersects(rect2)&&com!=component[k]){ component[k].setVisible(false);//this.remove(component[k]);}}}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mouseClicked(MouseEvent e){}public void mouseMoved(MouseEvent e){}public void mouseDragged(MouseEvent e){ Component com=null;if(e.getSource() instanceof Component){ com=(Component)e.getSource();a=com.getBounds().x;b=com.getBounds().y;x=e.getX(); //获取鼠标在事件源中的位置坐标y=e.getY();a=a+x;b=b+y;com.setLocation(a-x0,b-y0);}}}10.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class E{ public static void main(String args[]){ JFrame fr=new JFrame();fr.add(new MoveButton(),BorderLayout.CENTER);fr.setVisible(true);fr.setBounds(12,12,300,300);fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);fr.validate();}}class MoveButton extends JLayeredPane implements KeyListener { JButton b[]=new JButton[8];int x,y;MoveButton(){ setLayout(new FlowLayout());for(int i=0;i<8;i++){ b[i]=new JButton(""+i);b[i].addKeyListener(this);add(b[i]);}}public void keyPressed(KeyEvent e){ int moveDistance=1;Component com=(Component)e.getSource();int x=(int)com.getBounds().x;。

Java2实用教程课后答案-第三版-耿祥义-张跃平版

Java2实用教程课后答案-第三版-耿祥义-张跃平版

Java2实用教程(第三版)课后习题参考答案第1章 Java入门1. 开发与运行Java程序需要经过哪些主要步骤和过程?答:(1)编写Java源文件:使用文本编辑器(Edit或记事本),拓展名为。

java(2)编译Java源文件:使用Java编译器(javac。

exe)。

得到字节码文件*.class(3)运行Java程序:Java应用程序使用Java解释器(java。

exe)执行字节码文件;Java小应用程序使用支持Java标准的浏览器来执行.2。

怎样区分应用程序和小应用程序?应用程序的主类或小应用程序的主类必须用public修饰吗?答: ①应用程序必须有main方法,这个方法是程序执行的入口。

小应用程序没有main方法。

②应用程序的主类不一定用public修饰;小应用程序的主类必须用public修饰。

3. Java程序是由什么组成的?一个程序中必须要有public类吗?Java源文件的命名规则是怎样的?答:①Java程序由类组成.②应用程序可以没有public类;小应用程序一定有一个类是public类(主类)。

③应用程序:如果只有一个类,源文件名与该类的类名相同,拓展名为。

java;有多个类时,如果有public类(最多一个),源文件名与public类的类名相同,拓展名是.java;没有public类,源文件名与任何一个类的类名相同即可,拓展名为。

java.小应用程序:源文件名与主类的类名相同,拓展名是。

java。

4. 在运行小程序的HTML文件中可以使用codebase属性指定小程序的字节码所驻留的目录。

如果不使用codebase属性,小程序的字节码文件必须和运行它的HTML文件在同一目录中。

编写一个小程序并将小程序的字节码存放在某个目录中,比如C:\5000;把运行该小程序的HTML文件(注意其中的codebase属性):<applet code=你的小程序的字节码 width=200 height=300 codebase=C:\5000〉</applet>存放在另一个目录中。

Java2课后习题参考答案

Java2课后习题参考答案

Java2实用教程(第三版)课后习题参考答案第1章 Java入门1. 开发与运行Java程序需要经过哪些主要步骤和过程?答:(1)编写Java源文件:使用文本编辑器(Edit或记事本),拓展名为.java (2)编译Java源文件:使用Java编译器(javac.exe)。

得到字节码文件*.class (3)运行Java程序:Java应用程序使用Java解释器(java.exe)执行字节码文件;Java小应用程序使用支持Java标准的浏览器来执行。

2. 怎样区分应用程序和小应用程序?应用程序的主类或小应用程序的主类必须用public修饰吗?答:①应用程序必须有main方法,这个方法是程序执行的入口。

小应用程序没有main方法。

②应用程序的主类不一定用public修饰;小应用程序的主类必须用public修饰。

3. Java程序是由什么组成的?一个程序中必须要有public类吗?Java源文件的命名规则是怎样的?答:①Java程序由类组成。

②应用程序可以没有public类;小应用程序一定有一个类是public类(主类)。

③应用程序:如果只有一个类,源文件名与该类的类名相同,拓展名为.java;有多个类时,如果有public类(最多一个),源文件名与public类的类名相同,拓展名是.java;没有public类,源文件名与任何一个类的类名相同即可,拓展名为.java。

小应用程序:源文件名与主类的类名相同,拓展名是.java。

4. 在运行小程序的HTML文件中可以使用codebase属性指定小程序的字节码所驻留的目录。

如果不使用codebase属性,小程序的字节码文件必须和运行它的HTML 文件在同一目录中。

编写一个小程序并将小程序的字节码存放在某个目录中,比如C:\5000;把运行该小程序的HTML文件(注意其中的codebase属性):<applet code=你的小程序的字节码 width=200 height=300 codebase=C:\5000> </applet>存放在另一个目录中。

耿祥义张跃平java大学实用教程编程题标准答案

耿祥义张跃平java大学实用教程编程题标准答案

习题解答第一章作业题1.public class Hello{public static void main (String args[ ]){System.out.pintln(“早上好,good Morning”);}}2.import java.applet.*;import java.awt.*;public class Boy extends Applet {public void paint(Graphics g) {g.setColor(Color.blue);g.drawString("你好,hello",12,30);}}第二章作业题1.public class ZuoYe2_1{public static void main (String args[ ]){char c='а';System.out.println("字母"+c+"在unicode表中的顺序位置:"+(int)c);System.out.println("字母表:");while(c<='я'){System.out.print(" "+c);c=(char)(c+1);}}}2.import java.util.*;public class ZuoYe2_2{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);long chengji=1;int m=0;while(reader.hasNextInt()){int x=reader.nextInt();m=m+1;chengji=chengji*x;}System.out.println(m+"个数的乘积为"+chengji);}}第三章作业题1.import java.util.*;public class ZuoYe3_1{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);double y=0,x=0;x=reader.nextDouble();if(x<0)y=-1+2*x;else if(x==0)y=-1;else if(x>0)y=-1+3*x;System.out.println(y);}}2.public class ZuoYe3_2{public static void main(String args[]){int sum=0,m=3,n=7,a=1;while(a<=1000){if(a%m==0&&a%n==0)sum=sum+a;a++;}System.out.println("sum="+sum);}}3.public class ZuoYe3_3{public static void main(String args[]){long sum=0,a=8,item=a,n=10,i=1;for(i=1;i<=n;i++){ sum=sum+item;item=item*10+a;}System.out.println(sum);}}4.public class ZuoYe3_4{public static void main(String args[]){double sum=0,a=1,b=1,fuhao=1,item=a/b;int i=1;while(i<=1000){sum=sum+fuhao*item;i++;fuhao=fuhao*(-1);b=b+2;item=a/b;}System.out.println("sum="+sum);}}5.public class ZuoYe3_5{public static void main(String args[]){double sum=0,a=1;int i=1;while(i<=20){if(i>=10)sum=sum+a;i++;a=a*i;}System.out.println("sum="+sum);}}8.第四章作业题1.class DengCha{int start,d;DengCha(){}DengCha(int start,int d){this.start=start;this.d=d;}void setStart(int s){start=s;}void setD(int d){this.d=d;}int getSum(int n){int sum=0,i=1;while(i<=n){sum=sum+start;start=start+d;i++;}return sum;}}public class ZuoYe4_1{public static void main (String args[ ]){DengCha shulie=new DengCha(2,3);System.out.println(shulie.getSum(100));shulie.setStart(10);shulie.setD(5);System.out.println(shulie.getSum(9)); }}2.class Letter{public void printLetter(){for(char c='a';c<='z';c++)System.out.print(" "+c);}}public class ZuoYe4_2{public static void main (String args[ ]){Letter p=new Letter();p.printLetter();}}3.class SquareEquation{double a,b;static double c;double root1,root2;boolean boo;public SquareEquation(double a,double b,double c){ this.a=a;this.b=b;SquareEquation.c=c;if(a!=0){boo=true;}else{boo=false;}}public void getRoots(){if(boo){System.out.println("是一元2次方程");double disk=b*b-4*a*c;if(disk>=0){root1=(-b+Math.sqrt(disk))/(2*a);root2=(-b-Math.sqrt(disk))/(2*a);System.out.printf("方程的根:%f,%f\n",root1,root2);}else{System.out.printf("方程没有实根\n");}}else{System.out.println("不是一元2次方程");}}public void setCoefficient(double a,double b,double c){ this.a=a;this.b=b;SquareEquation.c=c;if(a!=0){boo=true;}else{boo=false;}}}public class ZuoYe4_3{public static void main(String args[ ]){SquareEquation equation1=new SquareEquation(4,5,1);SquareEquation equation2=new SquareEquation(3,5,-7);equation1.getRoots();equation2.getRoots();}}4.import java.util.Scanner;class A{int f(int m,int n){if(m*n<0){ System.out.println("有负数,程序退出");System.exit(0);}if(m<n){ int temp=m;m=n;n=temp;}int a=m,b=n;int r=m%n;while(r!=0){ m=n;n=r;r=m%n;}return n;}}class B{A a;B(){a=new A();}int g(int m,int n){int temp=a.f(m,n);return m*n/temp;}}public class ZuoYe4_4{public static void main (String args[ ]){Scanner reader=new Scanner(System.in);System.out.println("输入2个正整数,程序计算出它们的最大公约数和最小公倍数");System.out.print("输入第一个整数:");int m=reader.nextInt();System.out.print("输入第二个整数:");int n=reader.nextInt();A a=new A();B b=new B();System.out.println(m+"和"+n+"的最大公约数是"+a.f(m,n));System.out.println(m+"和"+n+"的最小公倍数是"+b.g(m,n));}}5.import java.applet.Applet;import java.awt.*;public class Example4_10 extends Applet{Button redbutton;public void init(){redbutton=new Button("我是一个红色的按钮");redbutton.setBackground(Color.red);redbutton.setForeground(Color.white);add(redbutton);}}第五章作业题1.import java.util.Scanner;class A{public int f(int m,int n){if(m<n){int temp=m;m=n;n=temp;}int r=m%n;while(r!=0){m=n;n=r;r=m%n;}return n;}}class B extends A{public int f(int m,int n){int division=super.f(m,n);return (m*n)/division;}}public class ZuoYe5_1{public static void main (String args[ ]){A a=new A();B b=new B();Scanner reader=new Scanner(System.in);System.out.println("输入2个整数,程序计算出它们的最大公约数和最小公倍数");System.out.print("输入第一个整数:");int m=reader.nextInt();System.out.print("输入第二个整数:");int n=reader.nextInt();if(m*n<0){ System.out.println("有负数,程序退出");System.exit(0);}System.out.printf("%d和%d的最大公约数是%d\n",m,n,a.f(m,n));System.out.printf("%d和%d的最小公倍数是%d\n",m,n,b.f(m,n));}}2.abstract class A{public abstract void f(int x);public abstract void g(int x,int y);public abstract double h(double x);}class A1 extends A{public void f(int x){System.out.println(x);}public void g(int x,int y){int z=x+y;System.out.println(z);}public double h(double x){return x*x;}}class A2 extends A{public void f(int x){System.out.println("Hello:"+x);}public void g(int x,int y){int z=x-y;System.out.println(z);}public double h(double x){return Math.sqrt(x);}}class A3 extends A{public void f(int x){System.out.println("你好:"+x);}public void g(int x,int y){double z=(double)x/y;System.out.println(z);}public double h(double x){return 1/x;}}public class ZuoYe5_2{public static void main(String args[ ]){A a=new A1();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A2();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A3();a.f(10);a.g(12,20);System.out.println(a.h(100));}}3.interface A{public abstract void f(int x);public abstract void g(int x,int y);public abstract double h(double x);}class A1 implements A{public void f(int x){System.out.println(x);}public void g(int x,int y){int z=x+y;System.out.println(z);}public double h(double x){return x*x;}}class A2 implements A{public void f(int x){System.out.println("Hello:"+x);}public void g(int x,int y){int z=x-y;System.out.println(z);}public double h(double x){return Math.sqrt(x);}}class A3 implements A{public void f(int x){System.out.println("你好:"+x);}public void g(int x,int y){double z=(double)x/y;System.out.println(z);}public double h(double x){return 1/x;}}public class ZuoYe5_3{public static void main(String args[ ]){A a=new A1();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A2();a.f(10);a.g(12,20);System.out.println(a.h(100));a=new A3();a.f(10);a.g(12,20);System.out.println(a.h(100));}}4.class Cubic{ double getCubic(int n){ return 0;}}abstract class Sqrt{ public abstract double getSqrt(int x); }class A{ void f(Cubic cubic){ double result=cubic.getCubic(3);System.out.println(result);}}public class ZuoYe5_4{ public static void main(String args[]) { A a=new A();a.f(new Cubic(){ double getCubic(int n){ return n*n*n;}});Sqrt ss=new Sqrt(){ public double getSqrt(int x){ return Math.sqrt(x);}};double m=ss.getSqrt(5);System.out.println(m);}}5.class IntegerException extends Exception{ String message;IntegerException(int m){ message="年龄"+m+"不合理";}public String toString(){ return message;}}class People{ private int age=1;public void setAge(int age) throws IntegerException{if(age>=160||age<=0)throw new IntegerException(age); //方法抛出异常,导致方法结束elsethis.age=age;}public int getAge(){ System.out.println("年龄"+age+"合理");return age;}}public class ZuoYe6_5{ public static void main(String args[]){ People wang=new People(),zhang=new People();try { wang.setAge(189);System.out.println(wang.getAge());}catch(IntegerException e){ System.out.println(e.toString());}try { zhang.setAge(28);System.out.println(zhang.getAge());}catch(IntegerException e){ System.out.println(e.toString());}}}第六章作业题1.import java.util.regex.*;import java.util.*;public class ZuoYe6_1{public static void main(String args[ ]){Scanner reader=new Scanner(System.in);String s1=reader.nextLine();Pattern p;Matcher m;p=pile("[24680]A[13579]{2}");m=p.matcher(s1);while(m.find()){String str=m.group();System.out.print("从"+m.start()+"到"+m.end()+"匹配模式子序列:");System.out.println(str);}}}2.import java.util.regex.*;import java.util.*;public class ZuoYe4_1{public static void main(String args[ ]){Scanner reader=new Scanner(System.in);String s1=reader.nextLine();Pattern p;Matcher m;p=pile("\\d+");m=p.matcher(s1);while(m.find()){String str=m.group();System.out.print(str);}}}第七章作业题1.import java.util.*;public class ZuoYe7_2{ public static void main(String args[]){int year,month;try{year=Integer.parseInt(args[0]);month=Integer.parseInt(args[1])+1;}catch(NumberFormatException e){year=2004;month=1;}System.out.println(" 日一二三四五六");Calendar 日历=Calendar.getInstance();日历.set(year,month,1);int 星期几=日历.get(Calendar.DAY_OF_WEEK)-1;String a[]=new String[星期几+31];for(int i=0;i<星期几;i++){ a[i]="**";}for(int i=星期几,n=1;i<星期几+31;i++){ if(n<=9)a[i]=String.valueOf(n)+" ";elsea[i]=String.valueOf(n) ;n++;}for(int i=0;i<a.length;i++){ if(i%7==0){ System.out.println("");}System.out.print(" "+a[i]);}}}2.class ZuoYe7_2{ public static void main(String args[]){int year1,month1,day1,year2,month2,day2;try{year1=Integer.parseInt(args[0]);month1=Integer.parseInt(args[1]);day1=Integer.parseInt(args[2]);year2=Integer.parseInt(args[3]);month2=Integer.parseInt(args[4]);day2=Integer.parseInt(args[5]);}catch(NumberFormatException e){year1=2009;month1=0;day1=1;year2=2008;month2=0;day2=1;}Calendar calendar=Calendar.getInstance();calendar.set(year1,month1,day1);long timeYear1=calendar.getTimeInMillis();calendar.set(year2,month2,day2);long timeYear2=calendar.getTimeInMillis();long 相隔天数=Math.abs((timeYear1-timeYear2)/(1000*60*60*24));System.out.println(""+year1+"年"+month1+"月"+day1+"日和"+year2+"年"+month2+"月"+day2+"日相隔"+相隔天数+"天");}}3.import java.math.*;public class ZuoYe4_1{public static void main(String args[]){BigInteger chengji=new BigInteger("1"),ONE=new BigInteger("1"),i=ONE,m=new BigInteger("10");while(pareTo(m)<=0){chengji=chengji.multiply(i);i=i.add(ONE);}System.out.println(chengji);}}4.import java.util.*;public class ZuoYe7_4{public static void main(String args[]){HashSet<Integer> A=new HashSet<Integer>(),B=new HashSet<Integer>(),tempSet=new HashSet<Integer>();A.add(new Integer(1));A.add(new Integer(2));A.add(new Integer(3));A.add(new Integer(4));B.add(new Integer(1));B.add(new Integer(3));B.add(new Integer(7));B.add(new Integer(9));B.add(new Integer(11));tempSet=(HashSet<Integer>)A.clone();tempSet.retainAll(B);System.out.println("交:");Iterator<Integer> iter=tempSet.iterator();while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue());}tempSet=(HashSet<Integer>)A.clone();tempSet.addAll(B);iter=tempSet.iterator();System.out.println("并:");while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue());}tempSet=(HashSet<Integer>)A.clone();tempSet.removeAll(B);System.out.println("差:");iter=tempSet.iterator();while(iter.hasNext()){Integer te=iter.next();System.out.printf("%d,",te.intValue());}}}5.import java.util.*;class MyKey implements Comparable{double number=0;MyKey(double number){this.number=number;}public int compareTo(Object b){MyKey st=(MyKey)b;if((this.number-st.number)==0){return -1;}else{return (int)((this.number-st.number)*1000);}}}class 硬盘{int size;double price;硬盘(int n, double p){size=n;price=p;}}public class ZuoYe4_1{public static void main(String args[ ]){int [] size={10,3,7,12,10,22,100,4,6,2};double [] price={1.2,9.56,2.4,9.3,16.77,12.66,7.4,5.5,5.6,8.9,1.9};硬盘[] s=new 硬盘[10];for(int i=0;i<s.length;i++)s[i]=new 硬盘(size[i],price[i]);TreeMap<MyKey,硬盘> treemap=new TreeMap<MyKey,硬盘>();for(int i=0;i<s.length;i++)treemap.put(new MyKey(s[i].size),s[i]);int number=treemap.size();System.out.println("树映射中有"+number+"个对象:");Collection<硬盘> collection=treemap.values();Iterator<硬盘> iter=collection.iterator();while(iter.hasNext()){硬盘te=iter.next();System.out.println(te.size+","+te.price);}treemap.clear();for(int i=0;i<s.length;i++)treemap.put(new MyKey(s[i].price),s[i]);number=treemap.size();System.out.println("树映射中有"+number+"个对象:");collection=treemap.values();iter=collection.iterator();while(iter.hasNext()){硬盘te=iter.next();System.out.println(te.size+","+te.price);}}}第八章作业题1.属于操作题目,省略2.参见例子8-23.参见例子8-34.参见例子8-10第九章作业题1.import java.io.*;import java.awt.*;import java.awt.event.*;public class ZuoYe9_1{ public static void main(String args[]){ int b;byte tom[]=new byte[25];try{ File f=new File("Example.java");FileInputStream in=new FileInputStream(f);while((b=in.read(tom,0,25))!=-1){ String s=new String (tom,0,b);System.out.print(s);}in.close();}catch(IOException e){ System.out.println("File read Error"+e);}}}2.import java.io.*;import java.util.*;public class ZuoYe9_2{public static void main(String args[]){Scanner reader=new Scanner(System.in);int b;try{FileOutputStream writefile=new FileOutputStream("line.txt");int line=1,n=10;System.out.println("输入"+n+"行文本,并存入磁盘:");while(line<=n){String s=reader.nextLine();byte buffer[]=s.getBytes();writefile.write(buffer,0,buffer.length);line++;}writefile.close();}catch(IOException e){System.out.println("Error "+e);}}}3.import java.io.*;public class ZuoYe9_3{public static void main(String args[ ]){int n=-1;CharArrayWriter out=new CharArrayWriter();for(char c='а';c<='я';c++){out.write(c);}CharArrayReader in=new CharArrayReader(out.toCharArray());try{ while((n=in.read())!=-1){if(n%2==0){System.out.printf("\n");}System.out.printf("\t位置%d,字符\'%c\'",n,(char)n);}}catch(IOException e){}}}4.import java.io.*;import java.util.*;public class ZuoYe9_4{public static void main(String args[]){try{FileOutputStream fos=new FileOutputStream("jerry.dat");DataOutputStream out_data=new DataOutputStream(fos);Scanner reader=new Scanner(System.in);for(int i=1;i<=10;i++){int x=reader.nextInt();out_data.writeInt(x);}out_data.close();}catch(IOException e){}try{FileInputStream fis=new FileInputStream("jerry.dat");DataInputStream in_data=new DataInputStream(fis);for(int i=1;i<=10;i++){int m=in_data.readInt();System.out.print(" "+m);}in_data.close();}catch(IOException e){}}}5.import java.io.*;import java.util.*;class Student implements Serializable{String name ;int number;Student(String name,int number){=name;this.number=number;}}public class ZuoYe9_5{public static void main(String args[]){List<Student> list=new LinkedList<Student>();List<Student> cloneList=null;for(int k=1;k<=12;k++)list.add(new Student("I am "+k,k));try{ FileOutputStream fileOut=new FileOutputStream("a.txt");ObjectOutputStream objectOut=new ObjectOutputStream(fileOut);objectOut.writeObject(list);FileInputStream fileIn=new FileInputStream("a.txt");ObjectInputStream objectIn=new ObjectInputStream(fileIn);cloneList=(List)objectIn.readObject();}catch(Exception event){System.out.println(event);}Iterator iter=cloneList.iterator();while(iter.hasNext()){Student te=(Student)iter.next();System.out.println(te.number+","+);}}}6.import java.io.*;public class ZuoYe9_6{ public static void main(String args[]){File f=new File("Xiti12_6.java");try{ RandomAccessFile random=new RandomAccessFile(f,"rw");random.seek(0);long m=random.length();while(m>=0){ m=m-1;random.seek(m);int c=random.readByte();if(c<=255&&c>=0){ System.out.print((char)c);}else{ m=m-1; //一个汉字占2个字节random.seek(m);byte cc[]=new byte[2];random.readFully(cc);System.out.print(new String(cc));}}random.close();}catch(IOException ee){}}}5.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_5{ public static void main(String args[]){ ComputerFrame fr=new ComputerFrame();fr.setTitle("计算");}}class ComputerFrame extends JFrame implements ActionListener { JTextField text1,text2,text3;JButton button1,button2,button3,button4;JLabel label;public ComputerFrame(){setLayout(new FlowLayout());text1=new JTextField(10);text2=new JTextField(10);text3=new JTextField(10);label=new JLabel(" ",JLabel.CENTER);label.setBackground(Color.green);add(text1);add(label);add(text2);add(text3);button1=new JButton("加");button2=new JButton("减");button3=new JButton("乘");button4=new JButton("除");add(button1);add(button2);add(button3);add(button4);button1.addActionListener(this);button2.addActionListener(this);button3.addActionListener(this);button4.addActionListener(this);setSize(400,320);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);validate();}public void actionPerformed(ActionEvent e){ double n;if(e.getSource()==button1){ double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1+n2;text3.setText(String.valueOf(n));label.setText("+");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button2){ double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1-n2;text3.setText(String.valueOf(n));label.setText("-");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button3){double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1*n2;text3.setText(String.valueOf(n));label.setText("*");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}else if(e.getSource()==button4){double n1,n2;try{ n1=Double.parseDouble(text1.getText());n2=Double.parseDouble(text2.getText());n=n1/n2;text3.setText(String.valueOf(n));label.setText("/");}catch(NumberFormatException ee){ text3.setText("请输入数字字符");}}validate();}}6.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_6{ public static void main(String args[]){ new WindowPanel();}}class Mypanel extends JPanel implements ActionListener { JButton button;JTextField text;Mypanel(){ button=new JButton(" ");text=new JTextField(12);add(button);add(text);button.addActionListener(this);}public void actionPerformed(ActionEvent e){ String name=text.getText();if(name.length()>0)button.setText(name);validate();}}class WindowPanel extends JFrame{ Mypanel panel1,panel2;WindowPanel(){ panel1=new Mypanel();panel2=new Mypanel();panel1.setBackground(Color.red);panel2.setBackground(Color.blue);add(panel1,BorderLayout.SOUTH);add(panel2,BorderLayout.NORTH);setSize(300,320);setVisible(true);validate();setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}7.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_7{ public static void main(String args[]){ new WindowColor();}}class WindowColor extends JFrame{ JButton button;JTextField text;JComboBox list;WindowColor(){ setLayout(new FlowLayout());button=new JButton("hello");button.setBackground(Color.pink);button.setForeground(new Color(12,26,200));text=new JTextField("how are you");text.setBackground(Color.yellow);text.setForeground(new Color(200,26,20));list=new JComboBox();list.addItem("Hello");list.addItem("Java");list.setBackground(Color.cyan);list.setForeground(new Color(100,100,100));add(list);add(button);add(text);setSize(300,320);setVisible(true);validate();setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}8.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Xiti8_8{ public static void main(String args[]){ MoveFrame f=new MoveFrame();f.setBounds(12,12,300,300);f.setVisible(true);f.setTitle("移动");f.validate();f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}class MoveFrame extends JFrame implements ActionListener{ JButton controlButton,movedButton;public MoveFrame(){ controlButton=new JButton("单击我运动另一个按钮");controlButton.addActionListener(this);movedButton=new JButton();movedButton.setBackground(new Color(12,200,34));setLayout(null);add(controlButton);add(movedButton);controlButton.setBounds(10,30,180,30);movedButton.setBounds(100,100,20,20);}public void actionPerformed(ActionEvent e){ int x=movedButton.getBounds().x;int y=movedButton.getBounds().y;x=x+5;y=y+1;movedButton.setLocation(x,y);if(x>200){ x=100;y=100;}}}9.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class E{ public static void main(String args[]){ JFrame fr=new JFrame();fr.add(new LP(),BorderLayout.CENTER);fr.setVisible(true);fr.setBounds(12,12,300,300);fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);fr.validate();}}class LP extends JLayeredPane implements MouseListener,MouseMotionListener { JButton button[];JTextField text[];int x,y,a,b,x0,y0;LP(){ setLayout(new FlowLayout());button=new JButton[8];for(int k=0;k<button.length;k++){ button[k]=new JButton("用鼠标拖动我");add(button[k]);button[k].addMouseListener(this);button[k].addMouseMotionListener(this);}text=new JTextField[10];for(int k=0;k<text.length;k++){ text[k]=new JTextField("用鼠标拖动我");text[k].addMouseListener(this);add(text[k]);text[k].addMouseMotionListener(this);}addMouseMotionListener(this);}public void mousePressed(MouseEvent e){ Component com=null;com=(Component)e.getSource();setLayer(com,JLayeredPane.DRAG_LAYER);a=com.getBounds().x;b=com.getBounds().y;x0=e.getX(); //获取鼠标在事件源中的位置坐标y0=e.getY();}public void mouseReleased(MouseEvent e){ Component com=null;com=(Component)e.getSource();setLayer(com,JLayeredPane.DEFAULT_LAYER);Component component[]=this.getComponents();for(int k=0;k<component.length;k++){ Rectangle rect1=component[k].getBounds();Rectangle rect2=com.getBounds();if(rect1.intersects(rect2)&&com!=component[k]){ component[k].setVisible(false);//this.remove(component[k]);}}}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void mouseClicked(MouseEvent e){}public void mouseMoved(MouseEvent e){}public void mouseDragged(MouseEvent e){ Component com=null;if(e.getSource() instanceof Component){ com=(Component)e.getSource();b=com.getBounds().y;x=e.getX(); //获取鼠标在事件源中的位置坐标y=e.getY();a=a+x;b=b+y;com.setLocation(a-x0,b-y0);}}}10.import java.awt.*;import java.awt.event.*;import javax.swing.*;public class E{ public static void main(String args[]){ JFrame fr=new JFrame();fr.add(new MoveButton(),BorderLayout.CENTER);fr.setVisible(true);fr.setBounds(12,12,300,300);fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);fr.validate();}}class MoveButton extends JLayeredPane implements KeyListener { JButton b[]=new JButton[8];int x,y;MoveButton(){ setLayout(new FlowLayout());for(int i=0;i<8;i++){ b[i]=new JButton(""+i);b[i].addKeyListener(this);add(b[i]);}}public void keyPressed(KeyEvent e){ int moveDistance=1;Component com=(Component)e.getSource();int x=(int)com.getBounds().x;。

java2实用教程(第三版)第七章课后习题答案(耿祥义)

java2实用教程(第三版)第七章课后习题答案(耿祥义)

import java.awt.*;import java.awt.event.*;import java.util.*;public class T7_4 {public static void main(String [] args) {FirstWindow win = new FirstWindow("计算的窗口");}}class FirstWindow extends Frame implements TextListener{ TextArea textA1,textA2;FirstWindow(String s) {setTitle(s);setLayout(new FlowLayout());textA1 = new TextArea(6,15);textA2 = new TextArea(6,15);add(textA1);add(textA2);textA1.addTextListener(this);setBounds(0,0,300,300);setVisible(true);validate();}public void textV alueChanged(TextEvent e) {String s = textA1.getText();StringTokenizer fenxi = new StringTokenizer(s," \n\r");int n = fenxi.countTokens();long sum=0;try{for(int i = 0; i<n; i++) {sum += Long.parseLong(fenxi.nextToken());}textA2.setText("总和" + String.valueOf(sum));double avg = (double)sum/n;textA2.append("\n平均数" + String.valueOf(avg));} catch (NumberFormatException e1) {//System.out.println("输入有误!");System.out.println(s);}}}import java.awt.*;import java.awt.event.*;public class T7_5 {public static void main(String [] args) {new MyFrame("挑单词");}}class MyFrame extends Frame implements ActionListener { TextArea ta1,ta2;Button btn;MyFrame (String s) {super(s);setLayout(new BorderLayout());ta1 = new TextArea(5,15);ta2 = new TextArea(5,15);btn = new Button("追加");btn.addActionListener(this);add(ta1,BorderLayout.EAST);add(ta2,BorderLayout.WEST);add(btn,BorderLayout.SOUTH);setBounds(100,100,300,200);setVisible(true);}public void actionPerformed(ActionEvent e) { String s = ta1.getSelectedText();ta2.append(s);}}//带关闭功能的窗口import java.awt.*;import java.awt.event.*;public class T7_6 {public static void main(String [] args) {new MathWindow("计算");}}class MathWindow extends Frame implements ActionListener {//定义一个类继承于Frame 并实现了接口ActionListenerButton btn_Add,btn_Sub,btn_Mul,btn_Mov;//定义四个表示运算的按钮TextField tf1,tf2,tf3;//定义三个文本框Label l1,l2;//定义两个标签MathWindow(String s) {super(s);//设置标题setLayout(new FlowLayout());//设置窗口模式btn_Add = new Button("加");btn_Sub = new Button("减");btn_Mul = new Button("乘");btn_Mov = new Button("除");//实例化四个表示运算的按钮tf1 = new TextField(8);tf2 = new TextField(8);tf3 = new TextField(8);//实例化三个文本框l1 = new Label("",1);l2 = new Label("=",1);//实例化两个标签add(tf1);add(l1);add(tf2);add(l2);add(tf3);add(btn_Add);add(btn_Sub);add(btn_Mul);add(btn_Mov);//将所需的组件加入到窗口中btn_Add.addActionListener(this);btn_Sub.addActionListener(this);btn_Mul.addActionListener(this);btn_Mov.addActionListener(this);//设置四个表示运算按钮的监视器为本窗口this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {dispose();//撤销当前窗口}});setBounds(100,100,500,80);//设置窗口大小setResizable(false);//设置窗口大小是否可由用户改变setVisible(true);//设置窗口的显示状态validate();//刷新}public void actionPerformed(ActionEvent e) {//实现ActionListener 接口的方法String s1 = tf1.getText();String s2 = tf2.getText();//获取两个文本框的内容try {long m = Long.parseLong(s1);long n = Long.parseLong(s2);//将获取的文本框的内容转换成长整型if(e.getSource() == btn_Add) {//判断事件的发生源并做出相应的处理l1.setText("+");tf3.setText(String.valueOf(m+n));}else if(e.getSource() == btn_Sub) {l1.setText("-");tf3.setText(String.valueOf(m-n));}else if (e.getSource() == btn_Mul) {l1.setText("x");tf3.setText(String.valueOf(m*n));}else if(e.getSource() == btn_Mov) {l1.setText("/");tf3.setText(String.valueOf(1.0*m/n));}else {System.exit(0);}}catch(NumberFormatException e1) {//异常处理System.out.println("输入数字字符串!");}}}import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;public class T7_7 {public static void main(String [] args) {WindowBox wb = new WindowBox("确定");}}class WindowBox extends Frame implements ActionListener { Box baseBox,boxV1,boxV2;TextField tf1,tf2,tf3;Button btn_OK;TextArea ta;WindowBox(String s) {super(s);tf1 = new TextField(12);tf2 = new TextField(12);tf3 = new TextField(12);boxV1 = Box.createV erticalBox();boxV1.add(new Label("姓名"));boxV1.add(Box.createV erticalStrut(8)); boxV1.add(new Label("E_mail"));boxV1.add(Box.createV erticalStrut(8)); boxV1.add(new Label("职业"));boxV2 = Box.createV erticalBox();boxV2.add(tf1);boxV2.add(Box.createV erticalStrut(8)); boxV2.add(tf2);boxV2.add(Box.createV erticalStrut(8)); boxV2.add(tf3);baseBox = Box.createHorizontalBox(); baseBox.add(boxV1);baseBox.add(Box.createHorizontalStrut(10)); baseBox.add(boxV2);setLayout(new FlowLayout());btn_OK = new Button("提交");btn_OK.addActionListener(this);ta = new TextArea(5,20);add(baseBox);add(btn_OK);add(ta);setBounds(120,125,200,260);setResizable(false);setVisible(true);}public void actionPerformed(ActionEvent e) {String regex = "\\w{1,}@\\w{1,}\56\\w{1,}";String name = tf1.getText();String email = tf2.getText();String pos = tf3.getText();if(!email.matches(regex)) {tf2.setText("非法E_mail地址");}else {String total = "姓名:" + name + "\nE_mail:" + email + "\n职业:" + pos;ta.append(total);}}}import java.awt.*;import java.awt.event.*;public class T7_8 {public static void main(String [] args) {new MyFrame("Panel");}}class MyPanel extends Panel implements ActionListener { TextField tf;Button btn;MyPanel() {setLayout(new GridLayout(2,1));tf = new TextField(10);btn = new Button("");add(tf);add(btn);btn.addActionListener(this);setVisible(true);}public void actionPerformed(ActionEvent e) { String label = tf.getText();btn.setLabel(label);}}class MyFrame extends Frame {MyPanel mp1,mp2;MyFrame(String s) {setLayout(new BorderLayout());mp1 = new MyPanel();mp2 = new MyPanel();add(mp1,BorderLayout.EAST);add(mp2,BorderLayout.WEST);pack();setVisible(true);}}import java.awt.*;import java.awt.event.*;public class T7_9 {public static void main(String [] args) { new WindowCanvas("矩形--画图");}}class Mycanvas extends Canvas {int x,y,width,height;Mycanvas() {setBackground(Color.cyan);}public void setX(int x) {this.x = x;}public void setY(int y) {this.y = y;}public void setWidth(int width) {this.width = width;}public void setHeight(int height) {this.height = height;}public void paint(Graphics g) {Color old = g.getColor();g.setColor(Color.red);g.fillRect(x,y,width,height);g.setColor(old);}}class WindowCanvas extends Frame implements ActionListener { Mycanvas canvas;TextField inputX,inputY,inputW,inputH;Button btn_ok;WindowCanvas(String s) {super(s);canvas = new Mycanvas();inputX = new TextField(5);inputY = new TextField(5);inputW = new TextField(5);inputH = new TextField(5);Panel pNorth = new Panel();Panel pSouth = new Panel();pNorth.add(new Label("矩形的坐标:(x,y)")); pNorth.add(inputX);pNorth.add(inputY);pSouth.add(new Label("矩形的宽和高:(w,h)")); pSouth.add(inputW);pSouth.add(inputH);btn_ok = new Button("确定");btn_ok.addActionListener(this);pSouth.add(btn_ok);add(pNorth,BorderLayout.NORTH);add(canvas,BorderLayout.CENTER);add(pSouth,BorderLayout.SOUTH); setBounds(50,50,600,700);setVisible(true);}public void actionPerformed(ActionEvent e) { int x = 0,y = 0,w = 0,h = 0;try{x = Integer.parseInt(inputX.getText());y = Integer.parseInt(inputY.getText());w = Integer.parseInt(inputW.getText());h = Integer.parseInt(inputH.getText());}catch(NumberFormatException e1) {x = 100;y = 100;w = 100;h = 100;}finally {canvas.setX(x);canvas.setY(y);canvas.setWidth(w);canvas.setHeight(h);canvas.repaint();}}}import java.awt.*;import java.awt.event.*;public class T7_10 {public static void main(String [] args) {new WindowList("商品信息");}}class WindowList extends Frame implements ItemListener,ActionListener {List list;TextArea ta;WindowList(String s) {super(s);list = new List(3,false);ta = new TextArea(40,10);list.add("lenovo");list.add("ThinkPad");list.add("IdeaPad");list.addItemListener(this);list.addActionListener(this);add(list,BorderLayout.NORTH);add(ta,BorderLayout.CENTER);setBounds(10,10,300,400);setVisible(true);}public void itemStateChanged(ItemEvent e) { String info = list.getSelectedItem();if(info.equals("lenovo")) {String dis = "价格:3000\n产地:中国";ta.setText(dis);}else if(info.equals("ThinkPad")) {String dis = "价格:7000\n产地:中国+美国";ta.setText(dis);}else {String dis = "价格:5000\n产地:中国香港";ta.setText(dis);}}public void actionPerformed(ActionEvent e) {String info = list.getSelectedItem();if(info.equals("lenovo")) {String dis = "家用笔记本电脑的首选,价格低廉,坚固耐用";ta.setText(dis);}else if(info.equals("ThinkPad")) {String dis = "商用笔记本电脑的首选,安全稳定,性能出色";ta.setText(dis);}else {String dis = "游戏用户的笔记本电脑首选,显卡高端,方便便携,经济实用,稳定出色";ta.setText(dis);}}}import java.awt.*;public class T7_11 {public static void main(String [] args) {new MyComponent("组件的前、背景色");}}class MyComponent extends Frame {Button btn;Label label;TextField tf;TextArea ta;MyComponent(String s) {super(s);setLayout(new GridLayout(2,2));btn = new Button("Button");btn.setBackground(Color.red);btn.setForeground(Color.yellow);add(btn);label = new Label("Label",1);label.setBackground(Color.green);label.setForeground(Color.black);add(label);tf = new TextField("TextField",10);tf.setBackground(Color.yellow);tf.setForeground(Color.darkGray);add(tf);ta = new TextArea("TextArea");ta.setBackground(Color.blue);ta.setForeground(Color.white);add(ta);pack();setVisible(true);}}import java.awt.*;import java.awt.event.*;public class T7_12 {public static void main(String [] args) {MyFrame1 mf = new MyFrame1("移动");}}class MyFrame1 extends Frame implements ActionListener { Button btn_L,btn_M;MyFrame1(String s) {super(s);setLayout(null);btn_L = new Button("移动按钮");btn_M = new Button("Moving!");btn_L.setLocation(10,30);btn_L.setSize(100,30);btn_M.setLocation(150,30);btn_M.setSize(50,20);btn_L.addActionListener(this);add(btn_L);add(btn_M);setBounds(0,100,510,400);setVisible(true);}public void actionPerformed (ActionEvent e) { Point p = btn_M.getLocation();p.x += 1;p.y += 1;btn_M.setLocation(p);}}import java.awt.*;import java.awt.event.*;public class T7_13 {public static void main(String [] args) { new MyFrame("改变圆形颜色");}}class MyCanvas extends Canvas {int x,y,r;Color c = Color.yellow;MyCanvas() {x = 200;y = 200;r = 50;setBackground(Color.yellow);}public void setC(Color c) {this.c = c;}public void paint(Graphics g) {Color old = g.getColor();g.setColor(c);g.fillOval(x,y,2*r,2*r);g.setColor(old);}}class MyFrame extends Frame implements ActionListener { Button btn_red,btn_blue,btn_green;MyCanvas can;MyFrame(String s) {super(s);setLayout(null);btn_red = new Button(" 红");btn_red.setBackground(Color.red);btn_red.setForeground(Color.white);btn_green = new Button(" 绿");btn_green.setBackground(Color.green);btn_green.setForeground(Color.white);btn_blue = new Button(" 蓝");btn_blue.setBackground(Color.blue);btn_blue.setForeground(Color.white);btn_red.setSize(50,30);btn_green.setSize(50,30);btn_blue.setSize(50,30);btn_red.setLocation(20+135,40); btn_green.setLocation(90+135,40); btn_blue.setLocation(160+135,40);btn_red.addActionListener(this); btn_green.addActionListener(this); btn_blue.addActionListener(this);add(btn_red);add(btn_green);add(btn_blue);can = new MyCanvas();can.setBounds(0,80,510,510);add(can);Canvas c = new Canvas();c.setBackground(Color.orange);c.setBounds(0,0,510,80);add(c);setVisible(true);setBounds(50,50,500,580);setResizable(false);}public void actionPerformed(ActionEvent e) { Object obj = e.getSource();if(obj == btn_red) {can.setC(Color.red);can.repaint();}else if(obj == btn_green) {can.setC(Color.green);can.repaint();}else {can.setC(Color.blue);can.repaint();}}}。

Java2实用教程(耿祥义第3版第7章)精品PPT课件

Java2实用教程(耿祥义第3版第7章)精品PPT课件

2.菜单条、菜单、菜单项
java.awt包中的Menubar类是负责创建菜单条的,即 Menubar的一个实例就是一个菜单条。Frame类有一 个将菜单条放置到窗口中的方法: setMenuBar(MenuBar bar);
java.awt包中的Menu类是负责创建菜单的,即Menu 的一个实例就是一个菜单
java.awt包的MunuItem类负责创建菜单项,即 MenuItem的一个实例就是一个菜单项
有关菜单的几个技巧
添加菜单分割线: menu.addSeparate();//分割线
复选框架菜单 如果想在选择这个菜单项时出现一个对号,可 以用CheckBoxMenuItem类创建这个菜单项。
Java 2实用教程(第3版)教学课件
配合例子代码一同使用 例子代码可登录下载
第7章 AWT组件及事件处理
7.1 Java窗口 7.2 文本框 7.3 内部类实例做监视器 7.4 按钮与标签 7.5 菜单项 7.6 文本区 7.7 面板 7.8 布局 7.9 画布
7.10 选择型组件 7.11 Component类的常用方法 7.12 窗口事件 7.13 鼠标事件 7.14 焦点事件 7.15 键盘事件 7.16 使用剪贴板 7.17 打印 7.18 综合实例
理解容器类(Container)和组件类(Component)
Java.awt包中一部分类的层次关系如图所示
组件和容器
组件:java把Component类创建的对象称为一 个组件。
容器:java把Container类创建的对象称为一个 容器。
可以向容器中添加组件。(容器和组件都是对 象)
public String getText() 文本框对象调用该方法 可以获取文本框中的文本。

Java程序设计实用教程习题答案作者耿祥义张跃平Java程序设计实用教程_邮电_习题答案.docx

Java程序设计实用教程习题答案作者耿祥义张跃平Java程序设计实用教程_邮电_习题答案.docx

习题11 • J ames Gosling2 .需3个步骤:1) 用文本编辑器编写源文件。

2) 使用javac编译源文件,得到字节码文件。

3) 使用解释器运行程序。

3 ・ set path= D:\jdk\bin;set classpath= D :\jdk\jre\lib\ rt.jar;4 ・ B) javac.exe5 • j ava 和class6. D) public static void main (String args[])习题21 . B ) int_ long ,D) $Boy262 .【代码1】,【代码3】是错误的3 . float常量必须用F或f为后缀。

double常量用D或d为后缀,但允许省略后缀。

4 .publ i c class E {publ i c s t a t i c voi d mai n( St r i ng a r gs []){ Sys t e m out. pr i nt I n( (i nt)'思');Sys t e m out. pr i nt I n( (i nt)'故');Sys t e m out. pr i nt I n( (i nt)'乡');}}习题31 . 110if-else语句书写的不够规范?2.不正正歪!!3 .public class Xiti3 {void giveMess(int number){ if(number^ = 9 |pumber= = 131 | number = 12){System.out.pri ntl n(number+ "是三等奖”);}else if(number= = 209 |number= = 596 |number==27) { System.out.println(number+ "是二等奖”);}else if(number= = 875 | number=316 |number= = 59) { System.out.println(number+"是一等奖");}else{System, out. pri ntl n("未中奖”);}}}4 •public class Xiti4 {public static void main (String args[]) { char cStart= *a \cE nd二'只: for(char c= cStart;c< = cE nd;c+ +) System.out.printf(,,%2c,,/c);System.out.pri ntln();for(char c= cStart;c< = cE n d;c+ +) System out pri ntf("%2c",(c+32));}}5 •public class XitiS {public static void main (String args[]) {double sum = OJtem = 1;int i = 1r n = 20;while(i< = n) {sum= sum+ item;i= i+1;item=}System, out. pri ntl n(H sum=n+ sum);}}6 •public class Xiti6 {public static void main(String args[]) {int sum= OJJ;for(i=1;i< = 1000;i+ + ) { for(j= 1,sum= O;j<i;j+ +){if(i%j==O) sum= surr^j;}if(surn= = i)System, out. printing 完数:”+ i); }}}public class Xiti7 {public static void main(String args[]) {int n= 1」=1jiecheng=1;long sum=0;while(true){jiecheng=1;for(i=1;i<=n;i++){jieche ng二jiecheng*i;}surrrsum+jiecheng;if(sum> 9999)break;叶+;}System.out.println("满足条件的最大整数:"+(n-1));}}习题41 .用类创建对象时。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
btn_OK = new Button("提交"); btn_OK.addActionListener(this); ta = new TextArea(5,20);
add(baseBox);
add(btn_OK); add(ta); setBounds(120,125,200,260); setResizable(false); setVisible(true); } public void actionPerformed(ActionEvent e) { String regex = "\\w{1,}@\\w{1,}\56\\w{1,}"; String name = tf1.getText(); String email = tf2.getText(); String pos = tf3.getText(); if(!email.matches(regex)) {
add(btn,BorderLayout.SOUTH); setBounds(100,100,300,200); setVisible(true); }
public void actionPerformed(ActionEvent e) { String s = ta1.getSelectedText(); ta2.append(s);
this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose();//撤销当前窗口 }
} );
setBounds(100,100,500,80);//设置窗口大小 setResizable(false);//设置窗口大小是否可由用户改变 setVisible(true);//设置窗口的显示状态
boxV1.add(new Label("姓名")); boxV1.add(Box.createVerticalStrut(8)); boxV1.add(new Label("E_mail")); boxV1.add(Box.createVerticalStrut(8)); boxV1.add(new Label("职业")); boxV2 = Box.createVerticalBox(); boxV2.add(tf1); boxV2.add(Box.createVerticalStrut(8)); boxV2.add(tf2); boxV2.add(Box.createVerticalStrut(8)); boxV2.add(tf3); baseBox = Box.createHorizontalBox(); baseBox.add(boxV1); baseBox.add(Box.createHorizontalStrut(10)); baseBox.add(boxV2); setLayout(new FlowLayout());
tf2.setText("非法 E_mail 地址"); } else {
String total = "姓名:" + name + "\nE_mail:" + email + "\n 职 业:" + pos;
ta.append(total); } } }
import java.awt.*; import java.awt.event.*;
} }
//带关闭功能的窗口 import java.awt.*; import javs T7_6 { public static void main(String [] args) { new MathWindow("计算"); }
}
class MathWindow extends Frame implements ActionListener {//定义一 个类继承于 Frame 并实现了接口 ActionListener
}
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*;
public class T7_7 { public static void main(String [] args) { WindowBox wb = new WindowBox("确定"); }
l1.setText("x"); tf3.setText(String.valueOf(m*n)); } else if(e.getSource() == btn_Mov) { l1.setText("/"); tf3.setText(String.valueOf(1.0*m/n)); } else { System.exit(0); } } catch(NumberFormatException e1) {//异常处理 System.out.println("输入数字字符串!"); } }
public class T7_8 { public static void main(String [] args) { new MyFrame("Panel"); }
} }
import java.awt.*; import java.awt.event.*; public class T7_5 {
public static void main(String [] args) { new MyFrame("挑单词");
} }
class MyFrame extends Frame implements ActionListener { TextArea ta1,ta2; Button btn; MyFrame (String s) { super(s); setLayout(new BorderLayout()); ta1 = new TextArea(5,15); ta2 = new TextArea(5,15); btn = new Button("追加"); btn.addActionListener(this); add(ta1,BorderLayout.EAST); add(ta2,BorderLayout.WEST);
}
class WindowBox extends Frame implements ActionListener { Box baseBox,boxV1,boxV2; TextField tf1,tf2,tf3; Button btn_OK; TextArea ta; WindowBox(String s) { super(s); tf1 = new TextField(12); tf2 = new TextField(12); tf3 = new TextField(12); boxV1 = Box.createVerticalBox();
} }
class FirstWindow extends Frame implements TextListener{ TextArea textA1,textA2; FirstWindow(String s) { setTitle(s); setLayout(new FlowLayout()); textA1 = new TextArea(6,15); textA2 = new TextArea(6,15); add(textA1); add(textA2); textA1.addTextListener(this); setBounds(0,0,300,300); setVisible(true); validate();
validate();//刷新
}
public void actionPerformed(ActionEvent e) {// 实 现 ActionListener 接口的方法
String s1 = tf1.getText(); String s2 = tf2.getText();//获取两个文本框的内容 try {
}
public void textValueChanged(TextEvent e) { String s = textA1.getText(); StringTokenizer fenxi = new StringTokenizer(s," \n\r"); int n = fenxi.countTokens(); long sum=0; try{ for(int i = 0; i<n; i++) { sum += Long.parseLong(fenxi.nextToken()); } textA2.setText("总和" + String.valueOf(sum)); double avg = (double)sum/n; textA2.append("\n 平均数 " + String.valueOf(avg)); } catch (NumberFormatException e1) { //System.out.println("输入有误!"); System.out.println(s); }
long m = Long.parseLong(s1); long n = Long.parseLong(s2);//将获取的文本框的内容转换 成长整型 if(e.getSource() == btn_Add) {//判断事件的发生源 并做 出相应的处理
l1.setText("+"); tf3.setText(String.valueOf(m+n)); } else if(e.getSource() == btn_Sub) { l1.setText("-"); tf3.setText(String.valueOf(m-n)); } else if (e.getSource() == btn_Mul) {
相关文档
最新文档