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

合集下载

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实用教程课后习题答案(第三版编程题)3. 编写应用程序,求1!+2!+?+10!。

答:class Fact {public static void main(String args[]) { int fact,sum=0; for(int i=1;ii++) { fact=1;for(int j=1;jj++)fact*=j; sum+=fact;}System.out.println(\到10的阶乘之和是:\}}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; < p></i;j++)>} if(w!=0)System.out.println(i+\是素数\}}}5. 分别用doDwhile和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;ii++) { fact=1;for(int j=1;jj++) fact*=j; sum+=1.0/fact;}System.out.println(sum);}}②doDwhile循环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实用教程课后习题答案(第三版编程题)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. 一个数如果恰好等于它的因子之和,这个数就称为“完数”。

JAVA程序设计实用教程课后习题简答(第3版)

JAVA程序设计实用教程课后习题简答(第3版)
{
if (n>0)
{
table = new int[n];
for (int i=0;i<n;i++)
table[i] = i+1;
permute(n);
}
else
table = null;
}
private void output()//输出数组元素
{
for (int i=0;i<table.length;i++)
2.实例成员方法与类成员方法
(1)两者声明时的差别。当一个类声明成员方法时,没有使用关键字static声明的为实例成员方法,使用关键字static声明的为类成员方法。
(2)两者方法体中语句的差别。类成员方法只能访问类成员变量;实例成员方法既可以访问类成员变量,也可以访问实例成员变量。在实例成员方法体中,可以使用this引用指代当前对象;而在类成员方法体中,则不能使用this引用。
3-8 this引用有什么作用?this引用有几种使用方法?
【答】Java类中成员方法与C语言中函数还有一个重要差别就是,Java类中每个成员方法都可以使用代词this引用调用该方法的当前对象自己,this引用有以下3种用法:
(1)this用于指代调用成员方法的当前对象自身,语法格式如下:
this
(2)通过this可以调用当前对象的成员变量,调用当前对象的成员方法。语法格式如下:
super.成员变量
(2)子类覆盖父类成员时,如需要访问父类同名成员方法时,需要使用supper指代父类的同名成员方法。语法如下:
super.成员方法([参数列表])
注意:super引用不能像this引用一样单独使用。
3-14什么是多态性?什么是方法的重载?方法的重载和覆盖有何区别?

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

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

读程序题第二章4. 下列哪些语句是错误的:int x = 8;byte b = 127;b = x;答:b=x语句错误;原因是高级别的变量赋值给低级别的变量时,一定要用显式转换即b=(byte)x; 。

5. 下列程序的输出结果是什么?public class E{public static void main(String args[]){long[] a={1,2,3,4};long[] b={100,200,300,400,500};b=a;System.out.println("数组b的长度:"+b.length);System.out.println("b[0]="+b[0]);}}答: 数组b的长度:4b[0]=16. 上机运行下列程序,注意观察输出结果。

public class E{public static void main(String args[]){for(int i=20302;i<20322;i++){System.out.println((char)i);}}}答: 低住佐佑佒体佔何佖佗佘余佚佛作佝佞佟你佡7. System.out.println(“你好”);可输出字符串,也可以使用System.out.println( )输出变量或表达式的值,只需使用并置符号“+”将变量、表达式或一个常数值与一个字符串并置即可,如: System.out.println(“”+x);System.out.println(“:”+123+“大于”+122);等。

上机调试下列程序,注意观察结果,特别注意System.out.print( )和System.out.println( )的区别。

public class OutputData{public static void main(String args[]){int x=234,y=432;System.out.println(x+"<"+(2*x));System.out.print("我输出结果后不回车");System.out.println("我输出结果后自动回车到下一行");System.out.println("x+y= "+(x+y));System.out.println(" "+x+y+"=");}}答: 234<468我输出结果后不回车我输出结果后自动回车到下一行x+y= 666=第三章1. 下列程序的输出结果是什么?public class E{public static void main(String args[]){char x='你',y='e',z='吃';if(x>'A'){y='爱';z='情';}elsey='我';z='她';System.out.println(" "+x+y+z);}}答: 你爱她2. 下列程序的输出结果是什么?public class E3{public static void main(String args[]){char c='\0';for(int i=1;i<=4;i++){switch(i){case 1:c='b';System.out.print(c);case 2:c='e';System.out.print(c);break;case 3:c='p';System.out.print(c);default:System.out.print("!");}}}}答:beep!!12.下列程序有什么错误?public class Takecare{int a=90;static float b=10.98f;public static void main(String args[]){float c=a+b;System.out.println("c="+c);}}答: 语句float c=a+b;错误。

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实用教程(第三版)课后习题参考答案

第4章类、对象和接口1. 类中的实例变量在什么时候会被分配内存空间?答: 当该类创建对象之后,实例变量才会被分配相应的内存空间。

2. 什么叫方法的重载?构造方法可以重载吗?答:①一个类中可以有多个方法具有相同的名字,但这些方法的参数必须不同,即或者是参数的个数不同,或者是参数的类型不同(方法的重载体现了多态性,即功能多态性)。

②构造方法可以重载。

3. 类中的实例方法可以操作类变量(static变量)吗?类方法(static方法)可以操作实例变量吗?答:①类中的实例方法可以操作类变量。

②类方法不可以操作实例变量4. 类中的实例方法可以用类名直接调用吗?答: 类中的实例方法不可以用类名直接调用。

5. 举例说明protected方法和友好方法的区别。

答: 当子类与父类不在同一个包中时,子类可以继承父类的protected方法;而友好方法此时则不能被子类继承。

6. 举例说明类变量和实例变量的区别。

答:⑴书写: 定义成员变量时,类变量有static修饰;实例变量没有static修饰。

例: class A{int x; //实例变量static int y; //类变量}⑵内存: 不创建对象,类的实例变量不会被分配内存空间;类变量被分配相应的内存空间。

不同对象的实例变量被分配不同的内存空间;不同对象的类变量被分配相同的内存空间。

任何一个对象改变类变量,其他对象的相应类变量也发生相应变化。

一个对象的实例变量发生改变,不影响其他对象的相应实例变量。

例: 执行语句: A1.x=10; A1.y=20;这时A2.x的值也是10;而A2.y的值保持原来的初值。

⑶使用: 类变量可以被类方法操作;而实例变量不能被类方法操作。

例: class A{int x;static int y;static void func(){b=10; //合法a=20; //非法}}类变量可以通过类名访问;实例变量不能通过类名访问。

例: class A{int x;static int y;}class B{public void func();{A.x=10; //非法A.y=20; //合法}}7. 子类将继承父类的哪些成员变量和方法?子类在什么情况下隐藏父类的成员变量和方法?在子类中是否允许有一个方法和父类的方法名字相同,而类型不同?答:①子类和父类在同一个包中时,子类可以继承父类的除private属性的所有方法和成员变量,当子类与父类不在同一个包中时,子类只能继承父类的protected和public属性的成员变量和方法。

java3课后习题答案

java3课后习题答案

java3课后习题答案Java3课后习题答案在学习Java3课程后,我们经常会遇到一些习题,这些习题旨在帮助我们巩固所学的知识,并提高我们的编程能力。

在这篇文章中,我们将为大家总结一些Java3课后习题的答案,希望能够帮助大家更好地理解和掌握Java编程。

1. 编写一个Java程序,计算并输出1到100之间所有偶数的和。

```javapublic class SumOfEvenNumbers {public static void main(String[] args) {int sum = 0;for (int i = 1; i <= 100; i++) {if (i % 2 == 0) {sum += i;}}System.out.println("1到100之间所有偶数的和为:" + sum);}}```2. 编写一个Java程序,找出一个整数数组中的最大值和最小值。

```javapublic class MaxMinInArray {public static void main(String[] args) {int[] array = {5, 3, 9, 1, 7, 4};int max = array[0];int min = array[0];for (int i = 1; i < array.length; i++) {if (array[i] > max) {max = array[i];}if (array[i] < min) {min = array[i];}}System.out.println("数组中的最大值为:" + max);System.out.println("数组中的最小值为:" + min);}}```3. 编写一个Java程序,实现一个简单的计算器,能够进行加减乘除运算。

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;。

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

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

JAVA实用教程(第三版)课后习题参考答案第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>存放在另一个目录中。

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

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

第八章第1题分四个部分分别建四个Java文本(1)public class Application {public static void main(String[] args) {new MyFrame("对话框实践");}}(2)import java.awt.*;import java.awt.event.*;public class ExceptionDialog extends Dialog implements ActionListener {Button btn;public ExceptionDialog(Frame f) {super(f,"Exception!",true);btn = new Button("close");Label label = new Label("输入格式有误!",Label.CENTER);add(label,BorderLayout.CENTER);add(btn,BorderLayout.SOUTH);btn.addActionListener(this);addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {setVisible(false);}});pack();setLocation(500,330);setResizable(false);}public void actionPerformed(ActionEvent e) {setVisible(false);}}(3)import java.awt.*;import java.awt.event.*;public class MyDialog extends Dialog {Button yes,no;Label label;String mess = null;public MyDialog(Frame f,boolean b) {super(f,"信息提示",b);label = new Label("您输入的数字> 1000!!!是否输入?");label.setAlignment(Label.CENTER);Container con = new Container();con.setLayout(new GridLayout(1,2));yes = new Button("OK");yes.setForeground(Color.red);no = new Button("Cancle");no.setForeground(Color.red);con.add(yes);con.add(no);add(label,BorderLayout.CENTER);add(con,BorderLayout.SOUTH);addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {setVisible(false);}});pack();setResizable(false);setLocation(510,330);}public void setMess(String mess) {this.mess = mess;bel.setText("您输入的数字" + this.mess + " > 1000!!!是否输入?");}public String getMess() {return this.mess;}public Button getYes() {return this.yes;}public Button getNo() {return this.no;}public void setHide() {yes.setVisible(false);no.setVisible(false);}}(4)import java.awt.*;import java.awt.event.*;public class MyFrame extends Frame implements ActionListener { MyDialog modelDialog;ExceptionDialog exception;TextField num;TextArea dis;public MyFrame(String title) {super(title);modelDialog = new MyDialog(this,true);exception = new ExceptionDialog(this);num = new TextField(20);dis = new TextArea(10,10);dis.setEnabled(false);add(num,BorderLayout.NORTH);add(dis,BorderLayout.CENTER);num.addActionListener(this);modelDialog.getY es().addActionListener(this);modelDialog.getNo().addActionListener(this);addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) { System.exit(1);}});setVisible(true);setLocation(500,300);setResizable(false);pack();}public void actionPerformed(ActionEvent e) { Object obj = e.getSource();if(obj == this.num) {String str = this.num.getText();try {if(Integer.parseInt(str) > 1000) {modelDialog.setMess(str);modelDialog.setVisible(true);}else {dis.append(str + "\n");}}catch (NumberFormatException e1) {exception.setVisible(true);}}if(obj == this.modelDialog.getY es()) {dis.append(this.modelDialog.getMess() + "\n");modelDialog.setVisible(false);}else if(obj == this.modelDialog.getNo()) {modelDialog.setVisible(false);}num.setText(null);}}第八章第2题分四个部分分别建5个Java文本(1)public class Application {public static void main(String[] args) {new MyFrame("Dialog");}}(2)import java.awt.*;import java.awt.event.*;public class MyFrame extends Frame implements Info ,ActionListener { TextField num;TextArea info;String mess;InfoDialog infoDialog;ExceptionDialog exceptionDialog;public MyFrame(String s) {super(s);infoDialog = new InfoDialog(this);exceptionDialog = new ExceptionDialog(this);num = new TextField(30);info = new TextArea(10,30);info.setEnabled(false);num.addActionListener(this);add(num,BorderLayout.NORTH);add(info,BorderLayout.CENTER);addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(1);}});pack();setLocation(480,300);setVisible(true);setResizable(false);}public void actionPerformed(ActionEvent e) { mess = e.getActionCommand();if(mess == null) {exceptionDialog.setVisible(true);}try {if(Long.parseLong(mess) > 1000) {infoDialog.notifyDialog();}else {.append(this.mess + "\n");}}catch(NumberFormatException e1) {exceptionDialog.setVisible(true);}this.num.setText(null);}public String getMess() {return this.mess;}public void setInfo() {.append(this.mess + "\n");}}(3)public interface DisDialog {public void notifyDialog();}(4)public interface Info {public String getMess();public void setInfo();}(5)import java.awt.*;import java.awt.event.*;public class InfoDialog extends Dialog implements ActionListener { Label label;Button yes,no;Info info;public InfoDialog(Frame f) {super(f,"info",true); = (Info)f;yes = new Button("ok");yes.addActionListener(this);no = new Button("no");no.addActionListener(this);Container con = new Container();con.setLayout(new FlowLayout());con.add(yes);con.add(no);add(con,BorderLayout.SOUTH);label = new Label("",Label.CENTER);add(label,BorderLayout.CENTER);addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(false);}});setSize(340,90);setLocation(500,330);setResizable(false);}public void actionPerformed(ActionEvent e) { Object obj = e.getSource();String str = info.getMess();this.validate();add(label,BorderLayout.CENTER);if(obj == yes) {info.setInfo();}setVisible(false);}public void notifyDialog() {bel.setText("您输入的数字" + info.getMess() + " > 1000!!!是否确认输入?");this.setVisible(true);}}。

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实用教程课后习题答案(第三版简单题)

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

第一章1. 开发与运行‎J ava程‎序需要经过‎哪些主要步‎骤和过程?答:(1)编写Jav‎a源文件:使用文本编‎辑器(Edit或‎记事本),拓展名为.java(2)编译Jav‎a源文件:使用Jav‎a编译器(javac‎.exe)。

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

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

小应用程序‎没有mai‎n方法。

②应用程序的‎主类不一定‎用publ‎i c修饰;小应用程序‎的主类必须‎用publ‎i c修饰。

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

②应用程序可‎以没有pu‎b lic类‎;小应用程序‎一定有一个‎类是pub‎l ic类(主类)。

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

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

第四章1. 类中的实例‎变量在什么‎时候会被分‎配内存空间‎?答: 当该类创建‎对象之后,实例变量才‎会被分配相‎应的内存空‎间。

2. 什么叫方法‎的重载?构造方法可‎以重载吗?答:①一个类中可‎以有多个方‎法具有相同‎的名字,但这些方法‎的参数必须‎不同,即或者是参‎数的个数不‎同,或者是参数‎的类型不同‎(方法的重载‎体现了多态‎性,即功能多态‎性)。

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

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循环long sum=0,data=8;for(int i=1;i<=10;i++){sum=sum+data;data=data*10+8;}System.out.println(sum);}}②while循环class TheSum{public static void main(String args[]){long sum=0,data=8,i=0;while(++i<=10){sum=sum+data;data=data*10+8;}System.out.println(sum);}}8. 编写应用程序,输出满足1+2+3+…+n<8888的最大正整数n。

java程序设计实用教程_(第3版)、_课后答案

java程序设计实用教程_(第3版)、_课后答案
【答】在程序中使用的数据大多需要经常变化,用常量值表示显然不够,因此每一种算法语言都提供常量和变量来存储数据。
为了确定常量或变量的数据性质、取值范围、以及它们占用的内存单元的字节数和它们参加的合法运算和操作。
6.什么是变量的作用域,声明变量时,如何确定变量的作用域?
【答】变量的作用域是指其作用范围。变量声明的位置决定了它的作用域
4.算术运算、关系运算、逻辑运算和位运算各有哪些运算符?
【答】算术运算:单目运算符有+(正)、—(负)、++(自增)、——(自减),双目运算符有+(加)、—(减)、*(乘)、/(除)、%(取余)
关系运算:=(等于)、!=(不等于)、>(大于)、<(小于)、>=(大于等于)、<=(小于等于)都是双目运算
number++;
}
k+=2;//测试下一个奇数是否是素数
} while(k<MAX);
output();
}
public static void output()//输出素数
{
System.out.println("All primes in 2~"+MAX+" are: ");
for (int i=0;i<number;i++)
j++;
}
i++;
}
}
System.out.println();
}
public static void init()//初始化数组,筛选法求素数
{
prime = new int[30];
prime[0]=2;//已知的最小素数

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

JAVA大学实用教程(第三版)课后习题答案(原版)
System.out.println("请输入等差数列开始值");
arithmetical.start=Reader.nextInt();
System.out.println("请输入等差数列的差值");
arithmetical.d=Reader.nextInt();
System.out.println("请输入等差数列求和的个数");
答:方法的重载是指一个类中可以有多个方法具有相同的名字,但这些方法的参数不同,或者参数的个数不同,或者参数的类型不同。构造方法可以重载。
9.请阐述为什么类方法不能调用实例方法?
答:对于类方法在该类加到内存时就分配了相应的入口地址,所以即使该类未创建对象,也可以通过类名调用类方法。而这时在类对象创建之前,实例方法还没有入口地址。还不知道一个方法从何处开始执行,当然不能调用。
如加入参数-private则可列出其全部的成员方法和成员变量。
如:
Javap–private java.awt.Button则可以列出Button类中全部的方法和成员变量。
18.下面程序中那个语句是错的?
class A
{
private float weight; //weight被修饰为private的float型变量。
If(x>9){
y=100;
Z=200;
}
Else
y=-100;
z=-200;
System.out.printf(“%d,%d,%d”,x,y,z);
输出:10,100,-200
8.下列for语句输出结果是什么?
For(int i=1; i<=4; i++){
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第一章Java语言概述2.“java编译器将源文件编译为的字节码文件是机器码”这句话正确吗?答:不正确3.java应用程序的主类必须含有怎样的方法?答:含有main方法4。

“java应用程序必须有一个类是public类”这句话正确吗?答;不正确,只能有一个public类5。

“java Applet程序的主类必须是public类”这句话正确吗?答:正确,因为java Applet主类必须是Applet类的子类并且是public 的类6。

请叙述java源程序的命名规则。

答:与public的类同名。

7。

源文件生成的字节码文件在运行时都加载到内存中吗?答:非也,动态随需要运行才加载。

8.面向对象的程序设计语言有那些基本特征?答:封装;继承;多态性。

9.在Java程序中有多个类文件时,用Java命令应该运行那个类?答:具有main方法的类第二章基本数据类型和数组4。

下列哪些语句是错的?Int x=120;Byte b=120;b=x;答:B=x;错应为b=(byte)x5。

下列哪些语句是错的?答:y=d;错,应y=(float)d6。

下列两个语句是等价的吗?Char x=97;Char x=…a‟;答:是等价的。

7。

下列system.out.printf语句输出结果是什么?Int a=97;Byte b1=(byte)128;Byte b2=(byte)(-129);System.out.printf(“%c,%d,%d”,a,b1,b2);如果输出语句改为:System.out.printf(“%d,%d,%d”,a,b1,b2);输出什么?答:输出a ,-128,127修改后输出97,-128,1278.数组是基本数据类型吗?怎样获取数组的长度?答:不是基本数据类型,是复合数据类型。

可以通过:数组名.length的方法获得数组长度9。

假设有两个int类型数组:Int[] a=new int[10];Int[] b=new int[8];b=a;A[0]=100;B[0]的值一定是100吗?答;一定,因为a数组与b数组引用相同。

10。

下列两个语句的作用等价吗?Int[] a={1,2,3,4,5,6,7,8};Int[] a=new int[8];答:不等价,前者有初值,后者指分配空间。

初值数组元素为0 11.有语句:int [] a={1,2,3},b={4,5};a=b;求a[0]=? b[1]=? 为什么?答:a[0]=4 ; b[1]=5 因为有相同的引用,同指向b[].12.Java语言使用_________编码,每个字符占___________字节________byte位Unicode 2 16第三章运算符、表达式与语句1。

下列语句输出的结果是什么?Int a=100, x,y;X=++a;Y=a--System.out.pri ntf(“%d, %d,%d”,x,y,a);答:101,101,1002。

下列语句那些有错误?Int x=0;X=5.0/2;Float y=12.5F;y=5.0/2;答:x=5.0/2; 错。

3。

下列语句那些有错?Byte x=32;Char c=…a‟;Int n=c-x;c=c-x;答:c=c-x;错应为int类型。

4下列语句正确的是A.表达式“12+56>34”的值是trueB.表达式“12+56||34”是非法表达式C.表达式“x+y=12”是非法表达式D.表达式“12+56>34”的值是13答:(A, C )5。

对于整数m,m<<1的结果一定是2m吗?答:不一定,高位有损失时,不是2m6.对于两个int整形变量Int m=120, n=240;那么m^m=?;m^n^n=?答:m^m=0; m^n^n=1207.下列System.out.printf语句输出的结果是什么?Int x=10, y=10, z=10;If(x>9){y=100;z=200;}Elsey=-100;z=-200;System.out.printf(“%d,%d,%d”,x,y,z);输出:10,100,-2008.下列for语句输出结果是什么?For(int i=1; i<=4; i++){Switch(i){Case 1: System.out.printf(“%c”,‟a‟);Case 2: System.out.printf(“%c”,‟b‟);Break;Case 3: System.out.printf(“%c”,‟c‟);Case 4: System.out.prin tf(“%c”,‟d‟);Break;}}输出:a,b, b,c,d,d9. 下列System.out.printf语句输出的结果是什么?Char a[]={…a‟,‟b‟,‟c‟,‟d‟,‟e‟};For(i=0; i<=a.length/2; i++){char c=a[i];a[i]=a[a.length-(i+1)];a [a.length-(i+1)]=c;}System.out.printf(“%c%c%c%c%c”a[0],a[1],a[2],a[3],a[4]); 输出:e,d,c,b,a10.下列System.out.printf语句输出的结果是什么?int a[]={3,4,1,2,-6};for(int i=0; i<a.length;i++){for(int j=i+1;j<a.length;j++){if(a[j]<a[i]){Int n=a[j]; a[j]=a[i]; a[i]=n;} } } System.out.printf(“%d,%d,%d,%d,%d”,a[0],a[1],a[2],a[3],a[4]);输出:-6,1,2,3,411.public class Tick{public static void main(String args[]){int a[]={3,4,1,2,-6};for(int i=0; i<a.length;i++){for(int j=i+1;j<a.length;j++){if(a[j]<a[i]){int n=a[j]; a[j]=a[i]; a[i]=n;} } } System.out.printf("%d,%d,%d,%d,%d",a[0],a[1],a[2],a[3],a[4]);}}第四章类与对象1.在声明类时,类名应遵循哪些习惯?答:首字母大写,望名知意2.类体内容有哪两种重要成员?答:成员变量,和成员方法。

3。

实例方法可以操作类变量吗?类方法可以操作实例变量吗?答:实例方法可以操作类变量。

而类方法不可以操作实例变量。

4.当类的字节码加载到内存时,类变量就一定分配了内存空间吗?答:实例成员变量不分配内存,而类变量一定分配内存。

5.类的实例变量在什么时候分配内存?答:声明之后,在用new关键字创建实例的时候才分配内存。

6.一个类的类变量被该类创建的所有对象共享吗?答:共享7.不同对象的实例变量分配的内存地址一定不同吗?答:当出现引用赋值语句时两个实例变量的内存地址相同。

8.什么叫方法的重载?构造方法可以重载吗?答:方法的重载是指一个类中可以有多个方法具有相同的名字,但这些方法的参数不同,或者参数的个数不同,或者参数的类型不同。

构造方法可以重载。

9.请阐述为什么类方法不能调用实例方法?答:对于类方法在该类加到内存时就分配了相应的入口地址,所以即使该类未创建对象,也可以通过类名调用类方法。

而这时在类对象创建之前,实例方法还没有入口地址。

还不知道一个方法从何处开始执行,当然不能调用。

10.请阐述,为什么类方法中不能操作实例成员变量?答:对于类方法在该类加到内存时就分配了相应的入口地址,所以即使该类未创建对象,也可以通过类名调用类方法。

而这时在类创建之前,实例成员变量还没有分配内存空间。

没内存空间当然无法操作。

11.实例方法可以用类名直接调用吗?答:不能,因为实例方法,用new创佳对象后才分配入口地址,而类名,一经声明就分配类名地址。

而这时对象创建之前实例方法还没有入口地址。

实例方法表现实例的功能,或改变实例变量。

用类调用改变那个实例的实例变量,表现那个实例的功能,不明确。

12.关键字this可以出现在构造方法中吗?可以出现在实例方法中吗?可以出现在类方法中吗?答:可以出现在构造方法中,代表该类构造方法所创造出的对象。

可以出现在实例方法中,代表使用该方法的当前对象。

This不能出现在类方法中,因为类方法是通过类名调用的。

13.源文件声明编写的类一定在同一个包中吗?答:不一定,当不在同一包中时,可用import语句将其所在的包引入该源文件中。

14.“import java.awt.*”与“import java.awt.Button”有什么不同?答:前者引入了awt包中的所有类,后者只引入了Button一个类。

15.程序中使用了“import java.util.*;”程序运行时,是要加载java.util 包中的全部类到内存吗?答:不,只加载本程序用到的类到内存中,因为java程序是动态加载,字节码类文件。

16.有哪几种访问权限修饰符?说出一种的作用。

答:访问权限修饰符有public, private,protected.Private作用是只允许本类的对象访问。

17.怎样反编译一个类?答:使用SDK提供的反编译器javap.exe文件可以实现将字节码文件反编译为源码文件。

可查看源码中public方法和public成员变量的名字。

如加入参数-private则可列出其全部的成员方法和成员变量。

如:Javap –private java.awt.Button则可以列出Button类中全部的方法和成员变量。

18.下面程序中那个语句是错的?class A{private float weight; //weight被修饰为private的float型变量。

public float f(float a,float b) //方法f是public方法。

{ return a; } }public class B{void g(){A a=new A();a.weight=23f;a.f(3,4);} }答:a.weight=23f;错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 ZuoYe04_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));DengCha arithmetical=new DengCha();Scanner Reader=new Scanner(System.in);System.out.println("请输入等差数列开始值");arithmetical.start=Reader.nextInt();System.out.println("请输入等差数列的差值");arithmetical.d=Reader.nextInt();System.out.println("请输入等差数列求和的个数");int n=Reader.nextInt();System.out.println(n+"个数的和是"+arithmetical.getSum(n));}}3.编写一个类,该类封装了一元二次方程的属性和功能,即该类有刻画方程系数的3个成员变量和求根的方法。

相关文档
最新文档