Java实用教程(第5版)参考答案

Java实用教程(第5版)参考答案Java 实用教程 第 5 版 参考答案第 1 章 Java 入门一 问答题二 选择题三 阅读程序第 2 章基本数据类型与数组一 问答题二 选择题三 阅读或调试程序四 编写程序第 1 章 Java 入门一 问答题 1 Java 语言的主要贡献者是谁 JamesGosling 开发 Java 应用程序需要经过哪些主要步骤 需要 3 个步骤 1 用文本编辑器编写源文件 2 使用 javac 编译源文件 得到字节

第1章 Java入门

一、问答题

1.Java语言的主要贡献者是谁?

James Gosling

2.开发Java应用程序需要经过哪些主要步骤?

3.Java源文件是由什么组成的?一个源文件中必须要有public类吗?

源文件由若干个类所构成。对于应用程序,必须有一个类含有public static void main(String args[])的方法,含有该方法的类称为应用程序的主类。不一定,但至多有一个public类。

4.如果JDK的安装目录为D:\jdk,应当怎样设置path和classpath的值?

set classpath=D:\jdk\jre\lib\rt.jar;.;

5.Java源文件的扩展名是什么?Java字节码的扩展名是什么?

java和class

6.如果Java应用程序主类的名字是Bird,编译之后,应当怎样运行该程序?

java Bird

7.有哪两种编程风格,在格式上各有怎样的特点?

独行风格(大括号独占行)和行尾风格(左大扩号在上一行行尾,右大括号独占行)

二、选择题

B

D

三、阅读程序

阅读下列Java源文件,并回答问题。

public class Person { 
    void speakHello() { 
    System.out.print("您好,很高兴认识您"); System.out.println(" nice to meet you"); } } class Xiti { 
    public static void main(String args[]) { 
    Person zhang = new Person(); zhang.speakHello(); } } 

第2章 基本数据类型与数组

一、问答题

1. 什么叫标识符?标识符的规则是什么?false是否可以作为标识符。

2. 什么叫关键字?true和false是否是关键字?请说出6个关键字。

3. Java的基本数据类型都是什么?

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

4. float型常量和double型常量在表示上有什么区别?

5. 怎样获取一维数组的长度,怎样获取二维数组中一维数组的个数。

二、选择题

C

ADF

B

BE

【代码2】【代码3】【代码4】【代码5】

B

三、阅读或调试程序

1.上机运行下列程序,注意观察输出的结果。

public class E { 
    public static void main (String args[ ]) { 
    for(int i=20302;i<=20322;i++) { 
    System.out.println((char)i); } } } 

2.上机调试下列程序,注意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)); } } 

3.上机调试下列程序,了解基本数据类型数据的取值范围。

public class E { 
    public static void main(String args[]) { 
    System.out.println("byte取值范围:"+Byte.MIN_VALUE+"至"+Byte.MAX_VALUE); System.out.println("short取值范围:"+Short.MIN_VALUE+"至"+Short.MAX_VALUE); System.out.println("int取值范围:"+Integer.MIN_VALUE+"至"+Integer.MAX_VALUE); System.out.println("long取值范围:"+Long.MIN_VALUE+"至"+Long.MAX_VALUE); System.out.println("float取值范围:"+Float.MIN_VALUE+"至"+Float.MAX_VALUE); System.out.println("double取值范围:"+Double.MIN_VALUE+"至"+Double.MAX_VALUE); } } 

4.下列程序标注的【代码1】,【代码2】的输出结果是什么?

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); //【代码1】 System.out.println("b[0]="+b[0]); //【代码2】 } } 

5.下列程序标注的【代码1】,【代码2】的输出结果是什么?

public class E { 
    public static void main(String args[]) { 
    int [] a={ 
   10,20,30,40},b[]={ 
   { 
   1,2},{ 
   4,5,6,7}}; b[0] = a; b[0][1] = b[1][3]; System.out.println(b[0][3]); //【代码1】 System.out.println(a[1]); //【代码2】 } } 

四、编写程序

1.编写一个应用程序,给出汉字‘你’、‘我’、‘他’在Unicode表中的位置。

public class E { 
    public static void main(String args[]) { 
    System.out.println((int)'你'); System.out.println((int)'我'); System.out.println((int)'他'); } } 

2.编写一个Java应用程序,输出全部的希腊字母。

public class E { 
    public static void main (String args[ ]) { 
    char cStart='α',cEnd='ω'; for(char c=cStart;c<=cEnd;c++) System.out.print(" "+c); } } 

第3章 运算符、表达式和语句

一、问答题

1.关系运算符的运算结果是怎样的数据类型?

boolean

2.if语句中的条件表达式的值是否可以是int型?

不可以

3.while语句中的条件表达式的值是什么类型?

boolean

4.switch语句中必须有default选项码?

不是必须的

5.在while语句的循环体中,执行break语句的效果是什么?

结束while语句的执行

6.可以用for语句代替while语句的作用吗?

可以

二、选择题

A

public class E { 
    public static void main (String args[ ]) { 
    int m=10,n=0; while(【代码】) { 
    n++; } } } 

C

C

三、阅读程序

1.下列程序的输出结果是什么?

public class E { 
    public static void main (String args[ ]) { 
    char x='你',y='e',z='吃'; if(x>'A'){ 
    y='苹'; z='果'; } else y='酸'; z='甜'; System.out.println(x+","+y+","+z); } } 

你,苹,甜

2.下列程序的输出结果是什么?

public class E { 
    public static void main (String args[ ]) { 
    char c = '\0'; for(int i=1;i<=4;i++) { 
    switch(i) { 
    case 1: c = 'J'; 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("好"); } } } } 

Jeep好好

3.下列程序的输出结果是什么?

public class E { 
    public static void main (String []args) { 
    int x = 1,y = 6; while (y-->0) { 
    x--; } System.out.print("x="+x+",y="+y); } } 

x=-5,y=-1

四、编程序题

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

public class Xiti1 { 
    public static void main(String args[]) { 
    double sum=0,a=1; int i=1; while(i<=10) { 
    sum=sum+a; i++; a=a*i; } System.out.println("sum="+sum); } } 

2.编写一个应用程序求100以内的全部素数。

public class Xiti2 { 
    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); } } } } 

3.分别用do-while和for循环计算1+1/2!+1/3!+1/4!… … 的前20项和。

class Xiti3 { 
    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); } } 

4.一个数如果恰好等于它的因子之和,这个数就称为“完数”。编写应用程序求1000之内的所有完数。

public class Xiti4 { 
    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); } } } 

5.编写应用程序,使用for循环语句计算8+88+888…前10项之和。

public class Xiti5 { 
    public static void main(String args[]) { 
    int m=8,item=m,i=1; long sum=0; for(i=1,sum=0,item=m;i<=10;i++) { 
    sum=sum+item; item=item*10+m; } System.out.println(sum); } } 

6.编写应用程序,输出满足1+2+3…+n<8888的最大正整数n。

public class Xiti6 { 
    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)); } } 

第4章 类与对象

一、问答题

1.面向对象语言有哪三个特性?

封装、继承和多态。

2.类名应当遵守怎样的编程风格?

当类名由几个单词复合而成时,每个单词的首字母使用大写。

3.变量和方法的名字应当遵守怎样的编程风格?

名字的首单词的首字母使用小写,如果变量的名字由多个单词组成,从第2个单词开始的其它单词的首字母使用大写。

4.类体内容中声明成员变量是为了体现对象的属性还是行为?

属性

5.类体内容中定义的非构造方法是为了体现对象的属性还是行为?

行为

6.什么时候使用构造方法?构造方法有类型吗?

7.类中的实例变量在什么时候会被分配内存空间?

用类创建对象时。

8.什么叫方法的重载?构造方法可以重载吗?

9.类中的实例方法可以操作类变量(static变量)吗?类方法(static方法)可以操作实例变量吗?

10.类中的实例方法可以用类名直接调用吗?

不可以。

11.简述类变量和实例变量的区别。

一个类通过使用new运算符可以创建多个不同的对象,不同的对象的实例变量将被分配不同的内存空间。所有对象的类变量都分配给相同的一处内存,对象共享类变量。

12.this关键字代表什么?this可以出现在类方法中吗?

二、选择题

B

D

D

class Dog { 
    Dog(int m){ 
    } Dog(double m){ 
    } int Dog(int m){ 
    return 23; } void Dog(double m){ 
    } } 

D

CD

6.下列A类中【代码1】~【代码5】哪些是错误的?

class Tom { 
    private int x = 120; protected int y = 20; int z = 11; private void f() { 
    x = 200; System.out.println(x); } void g() { 
    x = 200; System.out.println(x); } } public class A { 
    public static void main(String args[]) { 
    Tom tom = new Tom(); tom.x = 22; //【代码1】 tom.y = 33; //【代码2】 tom.z = 55; //【代码3】 tom.f(); //【代码4】 tom.g(); //【代码5】 } } 

【代码1】【代码4】

7.下列E类的类体中哪些【代码】是错误的。

class E { 
    int x; //【代码1】 long y = x; //【代码2】 public void f(int n) { 
    int m; //【代码3】  int t = n+m; //【代码4】  } } 

【代码4】

三、阅读程序

1.说出下列E类中【代码1】~【代码3】的输出结果。

class Fish { 
    int weight = 1; } class Lake { 
    Fish fish; void setFish(Fish s){ 
    fish = s; } void foodFish(int m) { 
    fish.weight=fish.weight+m; } } public class E { 
    public static void main(String args[]) { 
    Fish redFish = new Fish(); System.out.println(redFish.weight); //【代码1】 Lake lake = new Lake(); lake.setFish(redFish); lake.foodFish(120); System.out.println(redFish.weight); //【代码2】 System.out.println(lake.fish.weight); //【代码3】 } } 

2.请说出A类中System.out.println的输出结果。

class B { 
    int x = 100,y = 200; public void setX(int x) { 
    x = x; } public void setY(int y) { 
    this.y = y; } public int getXYSum() { 
    return x+y; } } public class A { 
    public static void main(String args[]) { 
    B b = new B(); b.setX(-100); b.setY(-200); System.out.println("sum="+b.getXYSum()); } } 

sum=-100

3.请说出A类中System.out.println的输出结果。

class B { 
    int n; static int sum=0; void setN(int n) { 
    this.n=n; } int getSum() { 
    for(int i=1;i<=n;i++) sum=sum+i; return sum; } } public class A { 
    public static void main(String args[]) { 
    B b1=new B(),b2=new B(); b1.setN(3); b2.setN(5); int s1=b1.getSum(); int s2=b2.getSum(); System.out.println(s1+s2); } } 

27

4.请说出E类中【代码1】,【代码2】的输出结果n的输出结果。

class A { 
    double f(int x,double y) { 
    return x+y; } int f(int x,int y) { 
    return x*y; } } public class E { 
    public static void main(String args[]) { 
    A a=new A(); System.out.println(a.f(10,10)); //【代码1】 System.out.println(a.f(10,10.0)); //【代码2】 } } 

5.上机实习下列程序,了解可变参数。

public class E { 
    public static void main(String args[]) { 
    f(1,2); f(-1,-2,-3,-4); //给参数传值时,实参的个数很灵活 f(9,7,6) ; } public static void f(int ... x){ 
    //x是可变参数的代表,代表若干个int型参数 for(int i=0;i<x.length;i++) { 
    //x.length是x代表的参数的个数 System.out.println(x[i]); //x[i]是x代表的第i个参数(类似数组) } } } 

6.类的字节码进入内存时,类中的静态块会立刻被执行。实习下列程序,了解静态块。

class AAA { 
    static { 
    //静态块 System.out.println("我是AAA中的静态块!"); } } public class E { 
    static { 
    //静态块 System.out.println("我是最先被执行的静态块!"); } public static void main(String args[]) { 
    AAA a= new AAA(); //AAA的字节码进入内存 System.out.println("我在了解静态(static)块"); } } 

四、编程题(参考例子7~9)

public class CPU { 
    int speed; int getSpeed() { 
    return speed; } public void setSpeed(int speed) { 
    this.speed = speed; } } 

HardDisk.java

public class HardDisk { 
    int amount; int getAmount() { 
    return amount; } public void setAmount(int amount) { 
    this.amount = amount; } } 

PC.java

public class PC { 
    CPU cpu; HardDisk HD; void setCPU(CPU cpu) { 
    this.cpu = cpu; } void setHardDisk(HardDisk HD) { 
    this.HD = HD; } void show(){ 
    System.out.println("CPU速度:"+cpu.getSpeed()); System.out.println("硬盘容量:"+HD.getAmount()); } } 

Test.java

public class Test { 
    public static void main(String args[]) { 
    CPU cpu = new CPU(); HardDisk HD=new HardDisk(); cpu.setSpeed(2200); HD.setAmount(200); PC pc =new PC(); pc.setCPU(cpu); pc.setHardDisk(HD); pc.show(); } } 

第5章 子类与继承

一、问答题

1.子类可以有多个父类吗?

不可以。

2.java.lang包中的Object类是所有其他类的祖先类吗?

是。

3.如果子类和父类不在同一个包中,子类是否继承父类的友好成员?

不继承。

4.子类怎样隐藏继承的成员变量?

声明与父类同名的成员变量。

5.子类重写方法的规则是怎样的?重写方法的目的是什么?

子类重写的方法类型和父类的方法的类型一致或者是父类的方法的类型的子类型,重写的方法的名字、参数个数、参数的类型和父类的方法完全相同。重写方法的目的是隐藏继承的方法,子类通过方法的重写可以把父类的状态和行为改变为自身的状态和行为。

6.父类的final方法可以被子类重写吗?

不可以。

7.什么类中可以有abstract方法?

abstract类。

8.对象的上转型对象有怎样的特点?

上转型对象不能操作子类新增的成员变量,不能调用子类新增的方法。上转型对象可以访问子类继承或隐藏的成员变量,可以调用子类继承的方法或子类重写的实例方法。

9.一个类的各个子类是怎样体现多态的?

通过重写方法。

10.面向抽象编程的目的和核心是什么?

面向抽象编程目的是为了应对用户需求的变化,核心是让类中每种可能的变化对应地交给抽象类的一个子类类去负责,从而让该类的设计者不去关心具体实现。

二、选择题

C

D

3.下列程序中注释的哪两个代码(A,B,C,D)是错误的(无法通过编译)?

class Father { 
    private int money =12; float height; int seeMoney(){ 
    return money ; //A } } class Son extends Father { 
    int height; int lookMoney() { 
    int m = seeMoney(); //B return m; } } class E { 
    public static void main(String args[]) { 
    Son erzi = new Son(); erzi.money = 300; //C erzi.height = 1.78F; //D } } 

CD

D

5.下列程序中注释的哪个代码(A,B,C,D)是错误的(无法通过编译)?

class A { 
    static int m; static void f(){ 
    m = 20 ; //A } } class B extends A { 
    void f() //B { 
    m = 222 ; //C  } } class E { 
    public static void main(String args[]) { 
    A.f(); // D  } } 

B

6.下列代码中标注的(A,B,C,D)中,哪一个是错误的?

abstract class Takecare { 
    protected void speakHello() { 
   } //A public abstract static void cry(); //B static int f(){ 
    return 0 ;} //C abstract float g(); //D } 

B

7.下列程序中注释的哪个代码(A,B,C,D)是错误的(无法通过编译)?

abstract class A { 
    abstract float getFloat (); //A void f() //B { 
    } } public class B extends A { 
    private float m = 1.0f; //C private float getFloat () //D { 
    return m; } } 

D

class A { 
    public float getNum() { 
    return 3.0f; } } public class B extends A { 
    【代码】 } 

B

class A { 
    public int i=0; A(int m) { 
    i = 1; } } public class B extends A { 
    B(int m) { 
    i = 2; } public static void main(String args[]){ 
    B b = new B(100); System.out.println(b.i); //【代码】 } } 

A

三、阅读程序

1.请说出E类中【代码1】,【代码2】的输出结果。

class A { 
    double f(double x,double y) { 
    return x+y; } } class B extends A { 
    double f(int x,int y) { 
    return x*y; } } public class E { 
    public static void main(String args[]) { 
    B b=new B(); System.out.println(b.f(3,5)); //【代码1】 System.out.println(b.f(3.0,5.0)); //【代码2】 } } 

2.说出下列B类中【代码1】,【代码2】的输出结果。

class A { 
    public int getNumber(int a) { 
    return a+1; } } class B extends A { 
    public int getNumber (int a) { 
    return a+100; } public static void main (String args[]) { 
    A a =new A(); System.out.println(a.getNumber(10)); //【代码1】 a = new B(); System.out.println(a.getNumber(10)); //【代码2】 } } 

3.请说出E类中【代码1】~【代码4】的输出结果。

class A { 
    double f(double x,double y) { 
    return x+y; } static int g(int n) { 
    return n*n; } } class B extends A { 
    double f(double x,double y) { 
    double m = super.f(x,y); return m+x*y; } static int g(int n) { 
    int m = A.g(n); return m+n; } } public class E { 
    public static void main(String args[]) { 
    B b = new B(); System.out.println(b.f(10.0,8.0)); //【代码1】 System.out.println(b.g(3)); //【代码2】 A a = new B(); System.out.println(a.f(10.0,8.0)); //【代码3】 System.out.println(a.g(3)); //【代码4】 } } 

4.请说出E类中【代码1】~【代码3】的输出结果。

class A { 
    int m; int getM() { 
    return m; } int seeM() { 
    return m; } } class B extends A { 
    int m ; int getM() { 
    return m+100; } } public class E { 
    public static void main(String args[]) { 
    B b = new B(); b.m = 20; System.out.println(b.getM()); //【代码1】 A a = b; a.m = -100; // 上转型对象访问的是被隐藏的m  System.out.println(a.getM()); //【代码2】上转型对象调用的一定是子类重写的getM()方法 System.out.println(b.seeM()); //【代码3】子类继承的seeM()方法操作的m是被子类隐藏的m } } 

四、编程题(参考例子13)

在这里插入图片描述
编写主类Application(用户程序)
在主类Application的main方法中至少包含如下代码:
Simulator simulator = new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());










Animal.java

public abstract class Animal { 
    public abstract void cry(); public abstract String getAnimalName(); } 

Simulator.java

public class Simulator { 
    public void playSound(Animal animal) { 
    System.out.print("现在播放"+animal.getAnimalName()+"类的声音:"); animal.cry(); } } 

Dog.java

public class Dog extends Animal { 
    public void cry() { 
    System.out.println("汪汪...汪汪"); } public String getAnimalName() { 
    return "狗"; } } 

Cat.java

public class Cat extends Animal { 
    public void cry() { 
    System.out.println("喵喵...喵喵"); } public String getAnimalName() { 
    return "猫"; } } 

Application.java

public class Application { 
    public static void main(String args[]) { 
    Simulator simulator = new Simulator(); simulator.playSound(new Dog()); simulator.playSound(new Cat()); } } 

第6章 接口与实现

一、问答题

1.接口中能声明变量吗?

不能。

2.接口中能定义非抽象方法吗?

不能。

3.什么叫接口的回调?

可以把实现某一接口的类创建的对象的引用赋给该接口声明的接口变量中。那么该接口变量就可以调用被类实现的接口中的方法。

4.接口中的常量可以不指定初值吗?

不可以。

5.可以在接口中只声明常量,不声明抽象方法吗?

可以。

二、选择题

D

2.下列接口中标注的(A,B,C,D)中,哪两个是错误的?

interface Takecare { 
    protected void speakHello(); //A public abstract static void cry(); //B int f(); //C abstract float g(); //D } 

AB

3.将下列(A,B,C,D)哪个代码替换下列程序中的【代码】不会导致编译错误。

Apublic int f(){ 
   return 100+M;} B.int f(){ 
   return 100;} Cpublic double f(){ 
   return 2.6;}Dpublic abstract int f(); interface Com { 
    int M = 200; int f(); } class ImpCom implements Com { 
    【代码】 } 

A

三、阅读程序

1.请说出E类中【代码1】,【代码2】的输出结果。

interface A { 
    double f(double x,double y); } class B implements A { 
    public double f(double x,double y) { 
    return x*y; } int g(int a,int b) { 
    return a+b; } } public class E { 
    public static void main(String args[]) { 
    A a = new B(); System.out.println(a.f(3,5)); //【代码1】 B b = (B)a; System.out.println(b.g(3,5)); //【代码2】 } } 

2.请说出E类中【代码1】,【代码2】的输出结果。

interface Com { 
    int add(int a,int b); } abstract class A { 
    abstract int add(int a,int b); } class B extends A implements Com{ 
    public int add(int a,int b) { 
    return a+b; } } public class E { 
    public static void main(String args[]) { 
    B b = new B(); Com com = b; System.out.println(com.add(12,6)); //【代码1】 A a = b; System.out.println(a.add(10,5)); //【代码2】 } } 

四、编程题(参考例子6)

public interface Animal { 
    public abstract void cry(); public abstract String getAnimalName(); } Simulator.java public class Simulator { 
    public void playSound(Animal animal) { 
    System.out.print("现在播放"+animal.getAnimalName()+"类的声音:"); animal.cry(); } } 

Dog.java

public class Dog implements Animal { 
    public void cry() { 
    System.out.println("汪汪...汪汪"); } public String getAnimalName() { 
    return "狗"; } } 

Cat.java

public class Cat implements Animal { 
    public void cry() { 
    System.out.println("喵喵...喵喵"); } public String getAnimalName() { 
    return "猫"; } } 

Application.java

public class Application { 
    public static void main(String args[]) { 
    Simulator simulator = new Simulator(); simulator.playSound(new Dog()); simulator.playSound(new Cat()); } } 

第7章 内部类与异常类

一、问答题

1. 内部类的外嵌类的成员变量在内部类中仍然有效吗?

有效。

2. 内部类中的方法也可以调用外嵌类中的方法吗?

可以。

3. 内部类的类体中可以声明类变量和类方法吗?

不可以。

4. 匿名类一定是内部类吗?

一定是。

二、选择题

1.下列代码标注的(A,B,C,D)中哪一个是错误的?

class OutClass { 
    int m = 1; static float x; //A class InnerClass { 
    int m =12; //B static float n =20.89f; //C  InnerClass(){ 
    } void f() { 
    m = 100; } } void cry() { 
    InnerClass tom = new InnerClass(); //D } } 

C

C

三、阅读程序

1.请说出下列程序的输出结果。

class Cry { 
    public void cry() { 
    System.out.println("大家好"); } } public class E { 
    public static void main(String args[]) { 
    Cry hello=new Cry() { 
    public void cry() { 
    System.out.println("大家好,祝工作顺利!"); } }; hello.cry(); } } 

大家好,祝工作顺利!

2.请说出下列程序的输出结果。

interface Com{ 
    public void speak(); } public class E { 
    public static void main(String args[]) { 
    Com p=new Com() { 
    public void speak() { 
    System.out.println("p是接口变量"); } }; p.speak(); } } 

p是接口变量

3.请说出下列程序的输出结果。

import java.io.IOException; public class E { 
    public static void main(String args[]){ 
    try { 
    methodA(); } catch(IOException e){ 
    System.out.print("你好"); return; } finally { 
    System.out.println(" fine thanks"); } } public static void methodA() throws IOException{ 
    throw new IOException(); } } 

你好 fine thanks

4.实习下列程序,了解静态内部类。

class RedCowForm { 
    static class RedCow { 
    //静态内部类是外嵌类中的一种静态数据类型 void speak() { 
    System.out.println("我是红牛"); } } } class BlackCowForm { 
    public static void main(String args[]) { 
    RedCowForm.RedCow red = new RedCowForm.RedCow(); //如果RedCom不是静态内部类,此代码非法 red.speak(); } } 

四、编写程序

第3章例子9的程序允许用户在键盘依次输入若干个数字(每输入一个数字都需要按回车键确认),程序将计算出这些数的和以及平均值。请在第3章的例子9中增加断言语句,当用户输入的数字大于100或小于0时,程序立刻终止执行,并提示这是一个非法的成绩数据。

import java.util.*; public class E { 
    public static void main (String args[ ]){ 
    Scanner reader = new Scanner(System.in); double sum = 0; int m = 0; while(reader.hasNextDouble()){ 
    double x = reader.nextDouble(); assert x< 100:"数据不合理"; m = m+1; sum = sum+x; } System.out.printf("%d个数的和为%f\n",m,sum); System.out.printf("%d个数的平均值是%f\n",m,sum/m); } } 

第8章 常用实用类

一、问答题

1.”\hello”是正确的字符串常量吗?

不是。”\\hello”是。

2.“你好KU”.length()和”\n\t\t”.length()的值分别是多少?

4和3。

3.“Hello”.equals(“hello”)和”java”.equals(“java”)的值分别是多少?

false和true。

4.“Bird”.compareTo(“Bird fly”)的值是正数还是负数?

负数。

5.“I love this game”.contains(“love”)的值是true吗?

是true。

6.“RedBird”.indexOf(“Bird”)的值是多少?“RedBird”.indexOf(“Cat”)的值是多少?

3和-1。

7.执行Integer.parseInt(“12.9”);会发生异常吗?

会发生NumberFormatException异常。

二、选择题

A

B

public class E{ 
    public static void main(String[] args){ 
    String strOne="bird"; String strTwo=strOne; strOne="fly"; System.out.println(strTwo); } } 

B

public class E { 
    public static void main (String args[]) { 
    String s1 = args[1]; String s2 = args[2]; String s3 = args[3]; System.out.println(s3); } } 

D

C

三、阅读程序

1.请说出E类中标注的【代码】的输出结果。

public class E { 
    public static void main (String[]args) { 
    String str = new String ("苹果"); modify(str); System.out.println(str); //【代码】 } public static void modify (String s) { 
    s = s + "好吃"; } } 

苹果

2.请说出E类中标注的【代码】的输出结果。

import java.util.*; class GetToken { 
    String s[]; public String getToken(int index,String str) { 
    StringTokenizer fenxi = new StringTokenizer(str); int number = fenxi.countTokens(); s = new String[number+1]; int k = 1; while(fenxi.hasMoreTokens()) { 
    String temp=fenxi.nextToken(); s[k] = temp; k++; } if(index<=number) return s[index]; else return null; } } class E { 
    public static void main(String args[]) { 
    String str="We Love This Game"; GetToken token=new GetToken(); String s1 = token.getToken(2,str), s2 = token.getToken(4,str); System.out.println(s1+":"+s2); //【代码】 } } 

Love:Game

3.请说出E类中标注的【代码1】,【代码2】的输出结果。

public class E { 
    public static void main(String args[]) { 
    byte d[]="abc我们喜欢篮球".getBytes(); System.out.println(d.length); //【代码1】 String s=new String(d,0,7); System.out.println(s); //【代码2】 } } 

4.请说出E类中标注的【代码】的输出结果。

class MyString { 
    public String getString(String s) { 
    StringBuffer str = new StringBuffer(); for(int i=0;i<s.length();i++) { 
    if(i%2==0) { 
    char c = s.charAt(i); str.append(c); } } return new String(str); } } public class E { 
    public static void main(String args[ ]) { 
    String s = ""; MyString ms = new MyString(); System.out.println(ms.getString(s)); //【代码】 } } 

13579

5.请说出E类中标注的【代码】,的输出结果。

public class E { 
    public static void main (String args[ ]) { 
    String regex = "\\djava\\w{1,}" ; String str1 = "88javaookk"; String str2 = "9javaHello"; if(str1.matches(regex)) { 
    System.out.println(str1); } if(str2.matches(regex)) { 
    System.out.println(str2); //【代码】  } } } 

9javaHello

6.上机实习下列程序,学习怎样在一个月内(一周内、一年内)前后滚动日期,例如,假设是3月(有31天)10号,如果在月内滚动,那么向后滚动10天就是3月20日,向后滚动25天,就是3月4号(因为只在该月内滚动)。如果在年内滚动,那么向后滚动25天,就是4月4号。

import java.util.*; public class RollDayInMonth { 
    public static void main(String args[]) { 
    Calendar calendar=Calendar.getInstance(); calendar.setTime(new Date()); String s = String.format("%tF(% 
    
    ,calendar 
    ) 
    ; System 
    .out 
    . 
    println 
    (s 
    ) 
    ; int n 
    = 
    25 
    ; System 
    .out 
    . 
    println 
    ( 
    "向后滚动(在月内)" 
    +n 
    + 
    "天" 
    ) 
    ; calendar 
    . 
    roll 
    (calendar 
    . 
    DAY_OF_MONTH 
    ,n 
    ) 
    ; s 
    = String 
    . 
    format 
    ( 
    "%tF(% 
      
      ,calendar 
      ) 
      ; System 
      .out 
      . 
      println 
      (s 
      ) 
      ; System 
      .out 
      . 
      println 
      ( 
      "再向后滚动(在年内)" 
      +n 
      + 
      "天" 
      ) 
      ; calendar 
      . 
      roll 
      (calendar 
      . 
      DAY_OF_YEAR 
      ,n 
      ) 
      ; s 
      = String 
      . 
      format 
      ( 
      "%tF(% 
        
        ,calendar 
        ) 
        ; System 
        .out 
        . 
        println 
        (s 
        ) 
        ; 
        } 
        } 
        
      
   

7.上机实习下列程序(学习Runtime类),注意观察程序的输出结果。

public class Test{ 
    public static void main(String args[]) { 
    Runtime runtime = Runtime.getRuntime(); long free = runtime.freeMemory(); System.out.println("Java虚拟机可用空闲内存 "+free+" bytes"); long total = runtime.totalMemory(); System.out.println("Java虚拟机占用总内存 "+total+" bytes"); long n1 = System.currentTimeMillis(); for(int i=1;i<=100;i++){ 
    int j = 2; for(;j<=i/2;j++){ 
    if(i%j==0) break; } if(j>i/2) System.out.print(" "+i); } long n2 = System.currentTimeMillis(); System.out.printf("\n循环用时:"+(n2-n1)+"毫秒\n"); free = runtime.freeMemory(); System.out.println("Java虚拟机可用空闲内存 "+free+" bytes"); total=runtime.totalMemory(); System.out.println("Java虚拟机占用总内存 "+total+" bytes"); } } 

四、编程题

1.字符串调用public String toUpperCase()方法返回一个字符串,该字符串把当前字符串中的小写字母变成大写字母;.字符串调用public String toLowerCase()方法返回一个字符串,该字符串把当前字符串中的大写字母变成小写字母。String类的public String concat(String str)方法返回一个字符串,该字符串是把调用该方法的字符串与参数指定的字符串连接。编写一个程序,练习使用这3个方法。

public class E { 
    public static void main (String args[ ]) { 
    String s1,s2,t1="ABCDabcd"; s1=t1.toUpperCase(); s2=t1.toLowerCase(); System.out.println(s1); System.out.println(s2); String s3=s1.concat(s2); System.out.println(s3); } } 

2.String类的public char charAt(int index)方法可以得到当前字符串index位置上的一个字符。编写程序使用该方法得到一个字符串中的第一个和最后一个字符。

public class E { 
    public static void main (String args[ ]) { 
    String s="ABCDabcd"; char cStart=s.charAt(0); char cEnd = s.charAt(s.length()-1); System.out.println(cStart); System.out.println(cEnd); } } 

3.计算某年、某月、某日和某年、某月、某日之间的天数间隔。要求年、月、日使用main方法的参数传递到程序中(见例子4)。

import java.util.*; public class E { 
    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=2012; month1=0; day1=1; year2=2018; month2=0; day2=1; } Calendar calendar=Calendar.getInstance(); calendar.set(year1,month1-1,day1); long timeYear1=calendar.getTimeInMillis(); calendar.set(year2,month2-1,day2); long timeYear2=calendar.getTimeInMillis(); long 相隔天数=Math.abs((timeYear1-timeYear2)/(1000*60*60*24)); System.out.println(""+year1+"年"+month1+"月"+day1+"日和"+ year2+"年"+month2+"月"+day2+"日相隔"+相隔天数+"天"); } } 

4.编程练习Math类的常用方法。

import java.util.*; public class E { 
    public static void main (String args[ ]) { 
    double a=0,b=0,c=0; a=12; b=24; c=Math.asin(0.56); System.out.println(c); c=Math.cos(3.14); System.out.println(c); c=Math.exp(1); System.out.println(c); c=Math.log(8); System.out.println(c); } } 

5.编写程序剔除一个字符串中的全部非数字字符,例如,将形如“ab123you”的非数字字符全部剔除,得到字符串“123”(参看例子10)。

public class E { 
    public static void main (String args[ ]) { 
    String str = "ab123you你是谁?"; String regex = "\\D+"; str = str.replaceAll(regex,""); System.out.println(str); } } 

6.使用Scanner类的实例解析字符串:”数学87分,物理76分,英语96分”中的考试成绩,并计算出总成绩以及平均分数(参看例子14)。

import java.util.*; public class E { 
    public static void main(String args[]) { 
    String cost = "数学87分,物理76分,英语96分"; Scanner scanner = new Scanner(cost); scanner.useDelimiter("[^0.]+"); double sum=0; int count =0; while(scanner.hasNext()){ 
    try{ 
    double score = scanner.nextDouble(); count++; sum = sum+score; System.out.println(score); } catch(InputMismatchException exp){ 
    String t = scanner.next(); } } System.out.println("总分:"+sum+"分"); System.out.println("平均分:"+sum/count+"分"); } } 

第9章 组件及事件处理

一、问答题

1.JFrame类的对象的默认布局是什么布局?

Frame容器的默认布局是BorderLayout布局。

2.一个容器对象是否可以使用add方法添加一个JFrame窗口?

不可以。

3.JTextField可以触发什么事件?

ActionEvent。

4.JTextArea中的文档对象可以触发什么类型的事件?

DocumentEvent。

5.MouseListener接口中有几个方法?

5个。

6.处理鼠标拖动触发的MouseEvent事件需使用哪个接口?

MouseMotionListener。

二、选择题

A

A

A

三、编程题

1.编写应用程序,有一个标题为“计算”的窗口,窗口的布局为FlowLayout布局。窗口中添加两个文本区,当我们在一个文本区中输入若干个数时,另一个文本区同时对你输入的数进行求和运算并求出平均值,也就是说随着你输入的变化,另一个文本区不断地更新求和及平均值。

import java.awt.*; import javax.swing.event.*; import javax.swing.*; import java.awt.event.*; public class E { 
    public static void main(String args[]) { 
    Computer fr=new Computer(); } } class Computer extends JFrame implements DocumentListener { 
    JTextArea text1,text2; int count=1; double sum=0,aver=0; Computer() { 
    setLayout(new FlowLayout()); text1=new JTextArea(6,20); text2=new JTextArea(6,20); add(new JScrollPane(text1)); add(new JScrollPane(text2)); text2.setEditable(false); (text1.getDocument()).addDocumentListener(this); setSize(300,320); setVisible(true); validate(); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public void changedUpdate(DocumentEvent e) { 
    String s=text1.getText(); String []a =s.split("[^0.]+"); sum=0; aver=0; for(int i=0;i<a.length;i++) { 
    try { 
    sum=sum+Double.parseDouble(a[i]); } catch(Exception ee) { 
   } } aver=sum/count; text2.setText(null); text2.append("\n和:"+sum); text2.append("\n平均值:"+aver); } public void removeUpdate(DocumentEvent e){ 
    changedUpdate(e); } public void insertUpdate(DocumentEvent e){ 
    changedUpdate(e); } } 

2.编写一个应用程序,有一个标题为“计算”的窗口,窗口的布局为FlowLayout布局。设计四个按钮,分别命名为“加”、“差”、“积、”、“除”,另外,窗口中还有三个文本框。单击相应的按钮,将两个文本框的数字做运算,在第三个文本框中显示结果。要求处理NumberFormatException异常。

import java.awt.*; import javax.swing.event.*; import javax.swing.*; import java.awt.event.*; public class E { 
    public static void main(String args[]) { 
    ComputerFrame fr=new ComputerFrame(); } } class ComputerFrame extends JFrame implements ActionListener { 
    JTextField text1,text2,text3; JButton buttonAdd,buttonSub,buttonMul,buttonDiv; 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); buttonAdd=new JButton("加"); buttonSub=new JButton("减"); buttonMul=new JButton("乘"); buttonDiv=new JButton("除"); add(buttonAdd); add(buttonSub); add(buttonMul); add(buttonDiv); buttonAdd.addActionListener(this); buttonSub.addActionListener(this); buttonMul.addActionListener(this); buttonDiv.addActionListener(this); setSize(300,320); setVisible(true); validate(); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public void actionPerformed(ActionEvent e) { 
    double n; if(e.getSource()==buttonAdd) { 
    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()==buttonSub) { 
    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()==buttonMul) { 
   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()==buttonDiv) { 
   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(); } } 

3.参照例子15编写一个体现MVC结构的GUI程序。首先编写一个封装梯形类,然后再编写一个窗口。要求窗口使用三文本框和一个文本区为梯形对象中的数据提供视图,其中三个文本框用来显示和更新梯形对象的上底、下底和高;文本区对象用来显示梯形的面积。窗口中有一个按钮,用户单击该按钮后,程序用3个文本框中的数据分别作为梯形对象的上底、下底和高,并将计算出的梯形的面积显示在文本区中。

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class E { 
    public static void main(String args[]){ 
    Window win = new Window(); win.setTitle("使用MVC结构"); win.setBounds(100,100,420,260); } } class Window extends JFrame implements ActionListener { 
    Lader lader; //模型 JTextField textAbove,textBottom,textHeight; //视图 JTextArea showArea; //视图 JButton controlButton; //控制器 Window() { 
    init(); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void init() { 
    lader = new Lader(); textAbove = new JTextField(5); textBottom = new JTextField(5); textHeight = new JTextField(5); showArea = new JTextArea(); controlButton=new JButton("计算面积"); JPanel pNorth=new JPanel(); pNorth.add(new JLabel("上底:")); pNorth.add(textAbove); pNorth.add(new JLabel("下底:")); pNorth.add(textBottom); pNorth.add(new JLabel("高:")); pNorth.add(textHeight); pNorth.add(controlButton); controlButton.addActionListener(this); add(pNorth,BorderLayout.NORTH); add(new JScrollPane(showArea),BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { 
    try{ 
    double above = Double.parseDouble(textAbove.getText().trim()); double bottom = Double.parseDouble(textBottom.getText().trim()); double height = Double.parseDouble(textHeight.getText().trim()); lader.setAbove(above) ; lader.setBottom(bottom); lader.setHeight(height); double area = lader.getArea(); showArea.append("面积:"+area+"\n"); } catch(Exception ex) { 
    showArea.append("\n"+ex+"\n"); } } } class Lader { 
    double above,bottom,height; public double getArea() { 
    double area = (above+bottom)*height/2.0; return area; } public void setAbove(double a) { 
    above = a; } public void setBottom(double b) { 
    bottom = b; } public void setHeight(double c) { 
    height = c; } } 

第10章 输入、输出流

一、问答题

1. 如果准备按字节读取一个文件的内容,应当使用FileInputStream流还是FileReader流?

使用FileInputStream。

2. FileInputStream流的read方法和FileReader流的read方法有何不同?

FileInputStream按字节读取文件,FileReader按字符读取文件。

3. BufferedReader流能直接指向一个文件吗?

不可以。

4. 使用ObjectInputStream和ObjectOutputStream类有哪些注意事项?

使用对象流写入或读入对象时,要保证对象是序列化的。

5. 怎样使用输入、输出流克隆对象?

使用对象流很容易得获取一个序列化对象的克隆,只需将该对象写入到对象输出流,那么用对象输入流读回的对象一定是原对象的一个克隆。

二、选择题

C

B

三、阅读程序

1.文件E.java的长度是51个字节,请说出E类中标注的【代码1】,【代码2】的输出结果。

import java.io.*; public class E { 
    public static void main(String args[]) { 
    File f = new File("E.java"); try{ 
    RandomAccessFile in = new RandomAccessFile(f,"rw"); System.out.println(f.length()); //【代码1】 FileOutputStream out = new FileOutputStream(f); System.out.println(f.length()); //【代码2】 } catch(IOException e) { 
    System.out.println("File read Error"+e); } } } 

2.请说出E类中标注的【代码1】~【代码4】的输出结果。

import java.io.*; public class E { 
    public static void main(String args[]) { 
    int n=-1; File f =new File("hello.txt"); byte [] a="abcd".getBytes(); try{ 
    FileOutputStream out=new FileOutputStream(f); out.write(a); out.close(); FileInputStream in=new FileInputStream(f); byte [] tom= new byte[3]; int m = in.read(tom,0,3); System.out.println(m); //【代码1】 String s=new String(tom,0,3); System.out.println(s); //【代码2】 m = in.read(tom,0,3); System.out.println(m); //【代码3】 s=new String(tom,0,3); System.out.println(s); //【代码4】 } catch(IOException e) { 
   } } } 

3.了解打印流。我们已经学习了数据流,其特点是用Java的数据类型读写文件,但使用数据流写成的文件用其它文件阅读器无法进行阅读(看上去是乱码)。PrintStream类提供了一个过滤输出流,该输出流能以文本格式显示Java的数据类型。上机实习下列程序:

import java.io.*; public class E { 
    public static void main(String args[]) { 
    try{ 
    File file=new File("p.txt"); FileOutputStream out=new FileOutputStream(file); PrintStream ps=new PrintStream(out); ps.print(12345.6789); ps.println("how are you"); ps.println(true); ps.close(); } catch(IOException e){ 
   } } } 

四、编写程序

1.使用RandomAccessFile流将一个文本文件倒置读出。

import java.io.*; public class E { 
    public static void main(String args[]) { 
    File f=new File("E.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; random.seek(m); byte cc[]=new byte[2]; random.readFully(cc); System.out.print(new String(cc)); } } } catch(Exception exp){ 
   } } } 

2.使用Java的输入、输出流将一个文本文件的内容按行读出,每读出一行就顺序添加行号,并写入到另一个文件中。

import java.io.*; public class E { 
    public static void main(String args[ ]) { 
    File file=new File("E.java"); File tempFile=new File("temp.txt"); try{ 
    FileReader inOne=new FileReader(file); BufferedReader inTwo= new BufferedReader(inOne); FileWriter tofile=new FileWriter(tempFile); BufferedWriter out= new BufferedWriter(tofile); String s=null; int i=0; s=inTwo.readLine(); while(s!=null) { 
    i++; out.write(i+" "+s); out.newLine(); s=inTwo.readLine(); } inOne.close(); inTwo.close(); out.flush(); out.close(); tofile.close(); } catch(IOException e){ 
   } } } 
import java.io.*; import java.util.*; public class E { 
    public static void main(String args[]) { 
    File file = new File("a.txt"); Scanner sc = null; double sum=0; int count = 0; try { 
    sc = new Scanner(file); sc.useDelimiter("[^0.]+"); while(sc.hasNext()){ 
    try{ 
    double price = sc.nextDouble(); count++; sum = sum+price; System.out.println(price); } catch(InputMismatchException exp){ 
    String t = sc.next(); } } System.out.println("平均价格:"+sum/count); } catch(Exception exp){ 
    System.out.println(exp); } } } 

第11章 JDBC与MySQL数据库

一、问答题

(1)怎样启动Mysql数据库服务器?

在MySQL安装目录的bin子目录下键入mysqld或mysqld -nt 启动MySQL数据库服务器。

(2)JDBC-MySQL数据库驱动的jar文件因该拷贝到哪个目录中?

复制到JDK的扩展目录中(即JAVA_HOME环境变量指定的JDK,见第1章的1.3.3),比如:E:\jdk1.8\jre\lib\ext。

(3)预处理语句的好处是什么?

减轻数据库内部SQL语句解释器的负担。

(4)什么叫事务,事务处理步骤是怎样的?

事务由一组SQL语句组成,所谓事务处理是指:应用程序保证事务中的SQL语句要么全部都执行,要么一个都不执行。事务处理步骤是调用:(1)连接对象用setAutoCommit()方法关闭自动提交模式,(2)连接对象用commit()方法处理事务,(3)连接对象用rollback()方法处理事务失败。

二、编程题

1.参照例子3,按出生日期排序mess表的记录。

import java.sql.*; import java.sql.*; public class BianCheng1 { 
    public static void main(String args[]) { 
    Connection con; Statement sql; ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; String sqlStr = "select * from mess order by birthday"; try { 
    sql=con.createStatement(); rs = sql.executeQuery(sqlStr); while(rs.next()) { 
    String number=rs.getString(1); String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close(); } catch(SQLException e) { 
    System.out.println(e); } } } 
import javax.swing.*; public class BianCheng2 { 
    public static void main(String args[]) { 
    String [] tableHead; String [][] content; JTable table ; JFrame win= new JFrame(); Query findRecord = new Query(); findRecord.setDatabaseName(args[0]); findRecord.setSQL("select * from "+args[1]); content = findRecord.getRecord(); tableHead=findRecord.getColumnName(); table = new JTable(content,tableHead); win.add(new JScrollPane(table)); win.setBounds(12,100,400,200); win.setVisible(true); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 

第12章 Java多线程机制

一、问答题

1.线程有几种状态?

4种状态:新建、运行、中断和死亡。

2.引起线程中断的常见原因是什么?

有4种原因的中断:(1)JVM将CPU资源从当前线程切换给其他线程,使本线程让出CPU的使用权处于中断状态。(2)线程使用CPU资源期间,执行了sleep(int millsecond)方法,使当前线程进入休眠状态。(3)线程使用CPU资源期间,执行了wait()方法,使得当前线程进入等待状态。(4)线程使用CPU资源期间,执行某个操作进入阻塞状态,比如执行读/写操作引起阻塞。

3.一个线程执行完run方法后,进入了什么状态?该线程还能再调用start方法吗?

死亡状态,不能再调用start()方法。

4.线程在什么状态时,调用isAlive()方法返回的值是false。

新建和死亡状态。

5.建立线程有几种方法?

两种方法:用Thread类或其子类。

6.怎样设置线程的优先级?

使用 setPrority(int grade)方法。

7.在多线程中,为什么要引入同步机制?

Java使我们可以创建多个线程,在处理多线程问题时,我们必须注意这样一个问题:当两个或多个线程同时访问同一个变量,并且一个线程需要修改这个变量。我们应对这样的问题作出处理,否则可能发生混乱。

8.在什么方法中wait()方法、notify()及notifyAll()方法可以被使用?

当一个线程使用的同步方法中用到某个变量,而此变量又需要其它线程修改后才能符合本线程的需要,那么可以在同步方法中使用wait()方法。使用wait方法可以中断方法的执行,使本线程等待,暂时让出CPU的使用权,并允许其它线程使用这个同步方法。其它线程如果在使用这个同步方法时不需要等待,那么它使用完这个同步方法的同时,应当用notifyAll()方法通知所有的由于使用这个同步方法而处于等待的线程结束等待。

不合理。

10.线程调用interrupt()的作用是什么?

“吵醒”休眠的线程。一个占有CPU资源的线程可以让休眠的线程调用interrupt 方法“吵醒”自己,即导致休眠的线程发生InterruptedException异常,从而结束休眠,重新排队等待CPU资源。

二、选择题

A

public class E { 
    public static void main(String args[]) { 
    Target target =new Target(); Thread thread =new Thread(target); thread.start(); } } class Target implements Runnable{ 
    public void run(){ 
    System.out.println("ok"); } } 

A

public class E { 
    public static void main(String args[]) { 
    Target target =new Target(); Thread thread =new Thread(target); target.run(); } } class Target implements Runnable{ 
    public void run(){ 
    System.out.println("ok"); } } 

B

三、阅读程序

1.上机运行下列程序,注意程序的运行效果(程序有两个线程:主线程和thread线程)。

public class E { 
    public static void main(String args[]) { 
    Target target =new Target(); Thread thread =new Thread(target); thread.start(); for(int i= 0;i<=10;i++) { 
    System.out.println("yes"); try{ 
    Thread.sleep(1000); } catch(InterruptedException exp){ 
   } } } } class Target implements Runnable{ 
    public void run() { 
    for(int i= 0;i<=10;i++) { 
    System.out.println("ok"); try{ 
    Thread.sleep(1000); } catch(InterruptedException exp){ 
   } } } } 

2.上机运行下列程序,注意程序的运行效果(注意该程序中只有一个主线程,thread线程并没有启动)。

public class E { 
    public static void main(String args[]) { 
    Target target =new Target(); Thread thread =new Thread(target); target.run(); for(int i= 0;i<=10;i++) { 
    System.out.println("yes"); try{ 
    Thread.sleep(1000); } catch(InterruptedException exp){ 
   } } } } class Target implements Runnable{ 
    public void run() { 
    for(int i= 0;i<=10;i++) { 
    System.out.println("ok"); try{ 
    Thread.sleep(1000); } catch(InterruptedException exp){ 
   } } } } 

3.上机运行下列程序,注意程序的运行效果(注意程序的输出结果)。

public class E { 
    public static void main(String args[]) { 
    Target target =new Target(); Thread thread1 =new Thread(target); Thread thread2 =new Thread(target); thread1.start(); try{ 
    Thread.sleep(1000); } catch(Exception exp){ 
   } thread2.start(); } } class Target implements Runnable{ 
    int i = 0; public void run() { 
    i++; System.out.println("i="+i); } } 

4.上机运行下列程序,注意程序的运行效果(注意和上面习题3的不同之处)。

public class E { 
    public static void main(String args[]) { 
    Target target1 =new Target(); Target target2 =new Target(); Thread thread1 =new Thread(target1); //与thread2的目标对象不同 Thread thread2 =new Thread(target2); //与thread1的目标对象不同 thread1.start(); try{ 
    Thread.sleep(1000); } catch(Exception exp){ 
   } thread2.start(); } } class Target implements Runnable{ 
    int i = 0; public void run() { 
    i++; System.out.println("i="+i); } } 

5.上机运行下列程序,注意程序的运行效果(计时器启动成功)。

import javax.swing.*; import java.util.Date; public class Ex { 
    public static void main(String args[]) { 
    javax.swing.Timer time=new javax.swing.Timer(500,new A()); time.setInitialDelay(0); time.start(); } } class A extends JLabel implements java.awt.event.ActionListener { 
    public void actionPerformed(java.awt.event.ActionEvent e){ 
    System.out.println(new Date()); } } 

Sun Apr 19 15:55:50 CST 2020

6.上机运行下列程序,注意程序的运行效果(计时器启动失败)。

import javax.swing.*; import java.util.Date; public class Ex { 
    public static void main(String args[]) { 
    javax.swing.Timer time=new javax.swing.Timer(500,new A()); time.setInitialDelay(0); time.start(); } } class A implements java.awt.event.ActionListener { 
    public void actionPerformed(java.awt.event.ActionEvent e){ 
    System.out.println(new Date()); } } 

7.在下列E类中【代码】输出结果是什么?

import java.awt.*; import java.awt.event.*; public class E implements Runnable { 
    StringBuffer buffer=new StringBuffer(); Thread t1,t2; E() { 
    t1=new Thread(this); t2=new Thread(this); } public synchronized void addChar(char c) { 
    if(Thread.currentThread()==t1) { 
    while(buffer.length()==0) { 
    try{ 
    wait(); } catch(Exception e){ 
   } } buffer.append(c); } if(Thread.currentThread()==t2) { 
    buffer.append(c); notifyAll(); } } public static void main(String s[]) { 
    E hello=new E(); hello.t1.start(); hello.t2.start(); while(hello.t1.isAlive()||hello.t2.isAlive()){ 
   } System.out.println(hello.buffer); //【代码】 } public void run() { 
    if(Thread.currentThread()==t1) addChar('A') ; if(Thread.currentThread()==t2) addChar('B') ; } } 

BA

8.上机实习下列程序,了解同步块的作用。

public class E { public static void main(String args[]) { Bank b=new Bank(); b.thread1.start(); b.thread2.start(); } } class Bank implements Runnable { Thread thread1,thread2; Bank() { thread1=new Thread(this); thread2=new Thread(this); } public void run() { printMess(); } public void printMess() { System.out.println(Thread.currentThread().getName()+"正在使用这个方法"); synchronized(this) { //当一个线程使用同步块时,其他线程必须等待 try { Thread.sleep(2000); } catch(Exception exp){} System.out.println(Thread.currentThread().getName()+"正在使用这个同步块"); } } } 

四、编程题

1.参照例子8,模拟三个人排队买票,张某、李某和赵某买电影票,售票员只有三张五元的钱,电影票5元钱一张。张某拿二十元一张的新人民币排在李的前面买票,李某排在赵的前面拿一张10元的人民币买票,赵某拿一张5元的人民币买票。

public class E { 
    public static void main(String args[]) { 
    Cinema a=new Cinema(); a.zhang.start(); a.sun.start(); a.zhao.start(); } } class TicketSeller //负责卖票的类。 { 
    int fiveNumber=3,tenNumber=0,twentyNumber=0; public synchronized void sellTicket(int receiveMoney) { 
    if(receiveMoney==5) { 
    fiveNumber=fiveNumber+1; System.out.println(Thread.currentThread().getName()+ "给我5元钱,这是您的1张入场卷"); } else if(receiveMoney==10) { 
    while(fiveNumber<1) { 
    try { 
    System.out.println(Thread.currentThread().getName()+"靠边等"); wait(); System.out.println(Thread.currentThread().getName()+"结束等待"); } catch(InterruptedException e) { 
   } } fiveNumber=fiveNumber-1; tenNumber=tenNumber+1; System.out.println(Thread.currentThread().getName()+ "给我10元钱,找您5元,这是您的1张入场卷"); } else if(receiveMoney==20) { 
    while(fiveNumber<1||tenNumber<1) { 
    try { 
    System.out.println(Thread.currentThread().getName()+"靠边等"); wait(); System.out.println(Thread.currentThread().getName()+"结束等待"); } catch(InterruptedException e) { 
   } } fiveNumber=fiveNumber-1; tenNumber=tenNumber-1; twentyNumber=twentyNumber+1; System.out.println(Thread.currentThread().getName()+ "给20元钱,找您一张5元和一张10元,这是您的1张入场卷"); } notifyAll(); } } class Cinema implements Runnable { 
    Thread zhang,sun,zhao; TicketSeller seller; Cinema() { 
    zhang=new Thread(this); sun=new Thread(this); zhao=new Thread(this); zhang.setName("张小有"); sun.setName("孙大名"); zhao.setName("赵中堂"); seller=new TicketSeller(); } public void run() { 
    if(Thread.currentThread()==zhang) { 
    seller.sellTicket(20); } else if(Thread.currentThread()==sun) { 
    seller.sellTicket(10); } else if(Thread.currentThread()==zhao) { 
    seller.sellTicket(5); } } } 

2.参照例子6,要求有3个线程:student1、student2和teacher,其中student1准备睡10分钟后再开始上课,其中student2准备睡一小时后再开始上课。teacher在输出3句“上课”后,吵醒休眠的线程student1;student1被吵醒后,负责再吵醒休眠的线程student2。

3.参照例子9,编写一个Java应用程序,在主线程中再创建3个线程:“运货司机”、“装运工”和“仓库管理员”。要求线程“运货司机”占有CPU资源后立刻联合线程“装运工”,也就是让“运货司机”一直等到“装运工”完成工作才能开车,而“装运工”占有CPU资源后立刻联合线程“仓库管理员”, 也就是让“装运工”一直等到“仓库管理员”打开仓库才能开始搬运货物。

第13章 Java网络编程

一、问答题

1.一个URL对象通常包含哪些信息?

一个URL对象通常包含最基本的三部分信息:协议、地址、资源。

2.URL对象调用哪个方法可以返回一个指向该URL对象所包含的资源的输入流。

URL对象调用InputStream openStream() 方法可以返回一个输入流,该输入流指向URL对象所包含的资源。通过该输入流可以将服务器上的资源信息读入到客户端。

3.客户端的Socket对象和服务器端的Socket对象是怎样通信的?

客户端的套接字和服务器端的套接字通过输入、输出流互相连接后进行通信。

4.ServerSocket对象调用accept方法返回一个什么类型的对象?

使用方法accept(),accept()会返回一个和客户端Socket对象相连接的Socket对象。accept方法会堵塞线程的继续执行,直到接收到客户的呼叫。

5.InetAddress对象使用怎样的格式来表示自己封装的地址信息?

域名/IP。

二、编程题

import java.net.*; import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Client { 
    public static void main(String args[]) { 
    new ComputerClient(); } } class ComputerClient extends Frame implements Runnable,ActionListener { 
    Button connection,send; TextField inputText,showResult; Socket socket=null; DataInputStream in=null; DataOutputStream out=null; Thread thread; ComputerClient() { 
    socket=new Socket(); setLayout(new FlowLayout()); Box box=Box.createVerticalBox(); connection=new Button("连接服务器"); send=new Button("发送"); send.setEnabled(false); inputText=new TextField(12); showResult=new TextField(12); box.add(connection); box.add(new Label("输入三角形三边的长度,用逗号或空格分隔:")); box.add(inputText); box.add(send); box.add(new Label("收到的结果:")); box.add(showResult); connection.addActionListener(this); send.addActionListener(this); thread=new Thread(this); add(box); setBounds(10,30,300,400); setVisible(true); validate(); addWindowListener(new WindowAdapter() { 
    public void windowClosing(WindowEvent e) { 
    System.exit(0); } }); } public void actionPerformed(ActionEvent e) { 
    if(e.getSource()==connection) { 
    try //请求和服务器建立套接字连接: { 
    if(socket.isConnected()) { 
   } else { 
    InetAddress address=InetAddress.getByName("127.0.0.1"); InetSocketAddress socketAddress=new InetSocketAddress(address,4331); socket.connect(socketAddress); in =new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); send.setEnabled(true); thread.start(); } } catch (IOException ee){ 
   } } if(e.getSource()==send) { 
    String s=inputText.getText(); if(s!=null) { 
    try { 
    out.writeUTF(s); } catch(IOException e1){ 
   } } } } public void run() { 
    String s=null; while(true) { 
    try{ 
    s=in.readUTF(); showResult.setText(s); } catch(IOException e) { 
    showResult.setText("与服务器已断开"); break; } } } } 

(2)服务器端

import java.io.*; import java.net.*; import java.util.*; public class Server { 
    public static void main(String args[]) { 
    ServerSocket server=null; Server_thread thread; Socket you=null; while(true) { 
    try{ 
    server=new ServerSocket(4331); } catch(IOException e1) { 
    System.out.println("正在监听"); //ServerSocket对象不能重复创建 } try{ 
    System.out.println(" 等待客户呼叫"); you=server.accept(); System.out.println("客户的地址:"+you.getInetAddress()); } catch (IOException e) { 
    System.out.println("正在等待客户"); } if(you!=null) { 
    new Server_thread(you).start(); //为每个客户启动一个专门的线程  } } } } class Server_thread extends Thread { 
    Socket socket; DataOutputStream out=null; DataInputStream in=null; String s=null; boolean quesion=false; Server_thread(Socket t) { 
    socket=t; try { 
    out=new DataOutputStream(socket.getOutputStream()); in=new DataInputStream(socket.getInputStream()); } catch (IOException e) { 
   } } public void run() { 
    while(true) { 
    double a[]=new double[3] ; int i=0; try{ 
    s=in.readUTF();//堵塞状态,除非读取到信息 quesion=false; StringTokenizer fenxi=new StringTokenizer(s," ,"); while(fenxi.hasMoreTokens()) { 
    String temp=fenxi.nextToken(); try{ 
    a[i]=Double.valueOf(temp).doubleValue();i++; } catch(NumberFormatException e) { 
    out.writeUTF("请输入数字字符"); quesion=true; } } if(quesion==false) { 
    double p=(a[0]+a[1]+a[2])/2.0; out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2]))); } } catch (IOException e) { 
    System.out.println("客户离开"); return; } } } } 
import java.net.*; import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Client { 
    public static void main(String args[]) { 
    new ChatClient(); } } class ChatClient extends Frame implements Runnable,ActionListener { 
    Button connection,send; TextField inputName,inputContent; TextArea chatResult; Socket socket=null; DataInputStream in=null; DataOutputStream out=null; Thread thread; String name=""; public ChatClient () { 
    socket=new Socket(); Box box1=Box.createHorizontalBox(); connection=new Button("连接服务器"); send=new Button("发送"); send.setEnabled(false); inputName=new TextField(6); inputContent=new TextField(22); chatResult=new TextArea(); box1.add(new Label("输入妮称:")); box1.add(inputName); box1.add(connection); Box box2=Box.createHorizontalBox(); box2.add(new Label("输入聊天内容:")); box2.add(inputContent); box2.add(send); connection.addActionListener(this); send.addActionListener(this); thread=new Thread(this); add(box1,BorderLayout.NORTH); add(box2,BorderLayout.SOUTH); add(chatResult,BorderLayout.CENTER); setBounds(10,30,400,280); setVisible(true); validate(); addWindowListener(new WindowAdapter() { 
    public void windowClosing(WindowEvent e) { 
    System.exit(0); } }); } public void actionPerformed(ActionEvent e) { 
    if(e.getSource()==connection) { 
    try { 
    if(socket.isConnected()) { 
   } else { 
    InetAddress address=InetAddress.getByName("127.0.0.1"); InetSocketAddress socketAddress=new InetSocketAddress(address,666); socket.connect(socketAddress); in =new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); name=inputName.getText(); out.writeUTF("姓名:"+name); send.setEnabled(true); if(!(thread.isAlive())) thread=new Thread(this); thread.start(); } } catch (IOException ee){ 
   } } if(e.getSource()==send) { 
    String s=inputContent.getText(); if(s!=null) { 
    try { 
    out.writeUTF("聊天内容:"+name+":"+s); } catch(IOException e1){ 
   } } } } public void run() { 
    String s=null; while(true) { 
    try{ 
    s=in.readUTF(); chatResult.append("\n"+s); } catch(IOException e) { 
    chatResult.setText("与服务器已断开"); try { 
    socket.close(); } catch(Exception exp) { 
   } break; } } } } 

服务器端ChatServer.java

import java.io.*; import java.net.*; import java.util.*; public class ChatServer { 
    public static void main(String args[]) { 
    ServerSocket server=null; Socket you=null; Hashtable peopleList; peopleList=new Hashtable(); while(true) { 
    try { 
    server=new ServerSocket(666); } catch(IOException e1) { 
    System.out.println("正在监听"); } try { 
    you=server.accept(); InetAddress address=you.getInetAddress(); System.out.println("客户的IP:"+address); } catch (IOException e) { 
   } if(you!=null) { 
    Server_thread peopleThread=new Server_thread(you,peopleList); peopleThread.start(); } else { 
    continue; } } } } class Server_thread extends Thread { 
    String name=null; Socket socket=null; File file=null; DataOutputStream out=null; DataInputStream in=null; Hashtable peopleList=null; Server_thread(Socket t,Hashtable list) { 
    peopleList=list; socket=t; try { 
    in=new DataInputStream(socket.getInputStream()); out=new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { 
   } } public void run() { 
    while(true) { 
    String s=null; try{ 
    s=in.readUTF(); if(s.startsWith("姓名:")) { 
    name=s; boolean boo=peopleList.containsKey(name); if(boo==false) { 
    peopleList.put(name,this); } else { 
    out.writeUTF("请换妮称:"); socket.close(); break; } } else if(s.startsWith("聊天内容")) { 
    String message=s.substring(s.indexOf(":")+1); Enumeration chatPersonList=peopleList.elements(); while(chatPersonList.hasMoreElements()) { 
    ((Server_thread)chatPersonList.nextElement()).out.writeUTF("聊天内容:"+ message); } } } catch(IOException ee) { 
    Enumeration chatPersonList=peopleList.elements(); while(chatPersonList.hasMoreElements()) { 
    try { 
    Server_thread th=(Server_thread)chatPersonList.nextElement(); if(th!=this&&th.isAlive()) { 
    th.out.writeUTF("客户离线:"+name); } } catch(IOException eee){ 
   } } peopleList.remove(name); try { 
    socket.close(); } catch(IOException eee){ 
   } System.out.println(name+"客户离开了"); break; } } } } 
import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.Timer; public class BroadCastWord extends Frame implements ActionListener { 
    int port; InetAddress group=null; MulticastSocket socket=null; Timer time=null; FileDialog open=null; Button select,开始广播,停止广播; File file=null; String FileDir=null,fileName=null; FileReader in=null; BufferedReader bufferIn=null; int token=0; TextArea 显示正在播放内容,显示已播放的内容; public BroadCastWord() { 
    super("单词广播系统"); select=new Button("选择要广播的文件"); 开始广播=new Button("开始广播"); 停止广播=new Button("停止广播"); select.addActionListener(this); 开始广播.addActionListener(this); 停止广播.addActionListener(this); time=new Timer(2000,this); open=new FileDialog(this,"选择要广播的文件",FileDialog.LOAD); 显示正在播放内容=new TextArea(10,10); 显示正在播放内容.setForeground(Color.blue); 显示已播放的内容=new TextArea(10,10); Panel north=new Panel(); north.add(select); north.add(开始广播); north.add(停止广播); add(north,BorderLayout.NORTH); Panel center=new Panel(); center.setLayout(new GridLayout(1,2)); center.add(显示正在播放内容); center.add(显示已播放的内容); add(center,BorderLayout.CENTER); validate(); try { 
    port=5000; group=InetAddress.getByName("239.255.0.0"); socket=new MulticastSocket(port); socket.setTimeToLive(1); socket.joinGroup(group); } catch(Exception e) { 
    System.out.println("Error: "+ e); } setBounds(100,50,360,380); setVisible(true); addWindowListener(new WindowAdapter() { 
    public void windowClosing(WindowEvent e) { 
    System.exit(0); } }); } public void actionPerformed(ActionEvent e) { 
    if(e.getSource()==select) { 
   显示已播放的内容.setText(null); open.setVisible(true); fileName=open.getFile(); FileDir=open.getDirectory(); if(fileName!=null) { 
    time.stop(); file=new File(FileDir,fileName); try { 
    file=new File(FileDir,fileName); in=new FileReader(file); bufferIn=new BufferedReader(in); } catch(IOException ee) { 
    } } } else if(e.getSource()==开始广播) { 
    time.start(); } else if(e.getSource()==time) { 
    String s=null; try { 
    if(token==-1) { 
    file=new File(FileDir,fileName); in=new FileReader(file); bufferIn=new BufferedReader(in); } s=bufferIn.readLine(); if(s!=null) { 
    token=0; 显示正在播放内容.setText("正在广播的内容:\n"+s); 显示已播放的内容.append(s+"\n"); DatagramPacket packet=null; byte data[]=s.getBytes(); packet=new DatagramPacket(data,data.length,group,port); socket.send(packet); } else { 
    token=-1; } } catch(IOException ee) { 
    } } else if(e.getSource()==停止广播) { 
    time.stop(); } } public static void main(String[] args) { 
    BroadCastWord broad=new BroadCastWord(); } } 

Receive.java

import java.net.*; import java.awt.*; import java.awt.event.*; public class Receive extends Frame implements Runnable,ActionListener { 
    int port; InetAddress group=null; MulticastSocket socket=null; Button 开始接收,停止接收; TextArea 显示正在接收内容,显示已接收的内容; Thread thread; boolean 停止=false; public Receive() { 
    super("定时接收信息"); thread=new Thread(this); 开始接收=new Button("开始接收"); 停止接收=new Button("停止接收"); 停止接收.addActionListener(this); 开始接收.addActionListener(this); 显示正在接收内容=new TextArea(10,10); 显示正在接收内容.setForeground(Color.blue); 显示已接收的内容=new TextArea(10,10); Panel north=new Panel(); north.add(开始接收); north.add(停止接收); add(north,BorderLayout.NORTH); Panel center=new Panel(); center.setLayout(new GridLayout(1,2)); center.add(显示正在接收内容); center.add(显示已接收的内容); add(center,BorderLayout.CENTER); validate(); port=5000; try{ 
    group=InetAddress.getByName("239.255.0.0"); socket=new MulticastSocket(port); socket.joinGroup(group); } catch(Exception e) { 
    } setBounds(100,50,360,380); setVisible(true); addWindowListener(new WindowAdapter() { 
    public void windowClosing(WindowEvent e) { 
    System.exit(0); } }); } public void actionPerformed(ActionEvent e) { 
    if(e.getSource()==开始接收) { 
    开始接收.setBackground(Color.blue); 停止接收.setBackground(Color.gray); if(!(thread.isAlive())) { 
    thread=new Thread(this); } try { 
    thread.start(); 停止=false; } catch(Exception ee) { 
    } } if(e.getSource()==停止接收) { 
    开始接收.setBackground(Color.gray); 停止接收.setBackground(Color.blue); thread.interrupt(); 停止=true; } } public void run() { 
    while(true) { 
    byte data[]=new byte[8192]; DatagramPacket packet=null; packet=new DatagramPacket(data,data.length,group,port); try { 
    socket.receive(packet); String message=new String(packet.getData(),0,packet.getLength()); 显示正在接收内容.setText("正在接收的内容:\n"+message); 显示已接收的内容.append(message+"\n"); } catch(Exception e) { 
    } if(停止==true) { 
    break; } } } public static void main(String args[]) { 
    new Receive(); } } 

第14章 图形、图像与音频

一、问答题

1.创建一个直线对象需要几个参数。

2个参数。

2.创建一个圆角矩形需要几个参数。

6个参数。

3.创建一个圆弧需要几个参数。

7个参数。

4.旋转一个图形需要哪几个步骤。

(1)创建AffineTransform对象,(2)进行旋转操作,(3)绘制旋转的图形。

二、编程题

1.编写一个应用程序,绘制五角形。

import java.awt.*; import javax.swing.*; class MyCanvas extends Canvas { 
    static int pointX[]=new int[5], pointY[]=new int[5]; public void paint(Graphics g) { 
    g.translate(200,200) ; //进行坐标变换,将新的坐标原点设置为(200,200)。 pointX[0]=0; pointY[0]=-120; double arcAngle=(72*Math.PI)/180; for(int i=1;i<5;i++) { 
    pointX[i]=(int)(pointX[i-1]*Math.cos(arcAngle)-pointY[i-1]*Math.sin(arcAngle)); pointY[i]=(int)(pointY[i-1]*Math.cos(arcAngle)+pointX[i-1]*Math.sin(arcAngle)); } g.setColor(Color.red); int starX[]={ 
   pointX[0],pointX[2],pointX[4],pointX[1],pointX[3],pointX[0]}; int starY[]={ 
   pointY[0],pointY[2],pointY[4],pointY[1],pointY[3],pointY[0]}; g.drawPolygon(starX,starY,6); } } public class E { 
    public static void main(String args[]) { 
    JFrame f=new JFrame(); f.setSize(500,450); f.setVisible(true); MyCanvas canvas=new MyCanvas(); f.add(canvas,"Center"); f.validate(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } 

2.编写一个应用程序绘制一条抛物线的一部分。

import java.awt.*; import javax.swing.*; import java.awt.geom.*; class MyCanvas extends Canvas { 
    public void paint(Graphics g) { 
    g.setColor(Color.red) ; Graphics2D g_2d=(Graphics2D)g; QuadCurve2D quadCurve= new QuadCurve2D.Double(2,10,51,90,100,10); g_2d.draw(quadCurve); quadCurve.setCurve(2,100,51,10,100,100); g_2d.draw(quadCurve); } } public class E { 
    public static void main(String args[]) { 
    JFrame f=new JFrame(); f.setSize(500,450); f.setVisible(true); MyCanvas canvas=new MyCanvas(); f.add(canvas,"Center"); f.validate(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } 

3.编写一个应用程序绘制双曲线的一部分.

import java.awt.*; import javax.swing.*; import java.awt.geom.*; class MyCanvas extends Canvas { 
    public void paint(Graphics g) { 
    g.setColor(Color.red) ; Graphics2D g_2d=(Graphics2D)g; CubicCurve2D cubicCurve= new CubicCurve2D.Double(0,70,70,140,140,0,210,70); g_2d.draw(cubicCurve); } } public class E { 
    public static void main(String args[]) { 
    JFrame f=new JFrame(); f.setSize(500,450); f.setVisible(true); MyCanvas canvas=new MyCanvas(); f.add(canvas,"Center"); f.validate(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } 

4.编写一个应用程序平移、缩放、旋转你喜欢的图形。

import java.awt.*; import javax.swing.*; import java.awt.geom.*; class Flower extends Canvas { 
    public void paint(Graphics g) { 
    Graphics2D g_2d=(Graphics2D)g; //花叶两边的曲线:  QuadCurve2D curve_1=new QuadCurve2D.Double(200,200,150,160,200,100); CubicCurve2D curve_2= new CubicCurve2D.Double(200,200,260,145,190,120,200,100); //花叶中的纹线: Line2D line=new Line2D.Double(200,200,200,110); QuadCurve2D leaf_line1= new QuadCurve2D.Double(200,180,195,175,190,170); QuadCurve2D leaf_line2= new QuadCurve2D.Double(200,180,210,175,220,170); QuadCurve2D leaf_line3= new QuadCurve2D.Double(200,160,195,155,190,150); QuadCurve2D leaf_line4= new QuadCurve2D.Double(200,160,214,155,220,150); //利用旋转来绘制花朵:  AffineTransform trans=new AffineTransform(); for(int i=0;i<6;i++) { 
    trans.rotate(60*Math.PI/180,200,200); g_2d.setTransform(trans); GradientPaint gradient_1= new GradientPaint(200,200,Color.green,200,100,Color.yellow); g_2d.setPaint(gradient_1); g_2d.fill(curve_1); GradientPaint gradient_2=new GradientPaint(200,145,Color.green,260,145,Color.red,true); g_2d.setPaint(gradient_2); g_2d.fill(curve_2); Color c3=new Color(0,200,0); g_2d.setColor(c3); g_2d.draw(line); g_2d.draw(leaf_line1); g_2d.draw(leaf_line2); g_2d.draw(leaf_line3); g_2d.draw(leaf_line4); } //花瓣中间的花蕾曲线: QuadCurve2D center_curve_1= new QuadCurve2D.Double(200,200,190,185,200,180); AffineTransform trans_1=new AffineTransform(); for(int i=0;i<12;i++) { 
    trans_1.rotate(30*Math.PI/180,200,200); g_2d.setTransform(trans_1); GradientPaint gradient_3= new GradientPaint(200,200,Color.red,200,180,Color.yellow); g_2d.setPaint(gradient_3); g_2d.fill(center_curve_1); } } } public class E { 
    public static void main(String args[]) { 
    JFrame f=new JFrame(); f.setSize(500,450); f.setVisible(true); Flower canvas=new Flower(); f.add(canvas,"Center"); f.validate(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } 

5.编写一个应用程序(利用图形的布尔运算)绘制各种样式的“月牙”。

import java.awt.*; import javax.swing.*; import java.awt.geom.*; class Moon extends Canvas { 
    public void paint(Graphics g) { 
    Graphics2D g_2d=(Graphics2D)g; Ellipse2D ellipse1= new Ellipse2D. Double (20,80,60,60), ellipse2= new Ellipse2D. Double (40,80,80,80); g_2d.setColor(Color.white); Area a1=new Area(ellipse1), a2=new Area(ellipse2); a1.subtract(a2); //"差" g_2d.fill(a1); } } public class E { 
    public static void main(String args[]) { 
    JFrame f=new JFrame(); f.setSize(500,450); f.setVisible(true); Moon moon=new Moon(); moon.setBackground(Color.black); f.add(moon,"Center"); f.validate(); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } 

第15章 泛型与集合框架

一、问答题

1.LinkedList链表和ArrayList数组表有什么不同?

LinkedList使用链式存储结构,ArrayList使用顺序存储结构。

2.为何使用迭代器遍历链表?

迭代器遍历在找到集合中的一个对象的同时,也得到待遍历的后继对象的引用,因此迭代器可以快速地遍历集合。

3.树集的节点是按添加的先后顺序排列的吗?

不是。

4.对于经常需要查找的数据,应当选用LinkedList,还是选用HashMap

来存储?

用HashMap

来存储。

二、阅读程序

1.在下列E类中System.out.println的输出结果是什么?

import java.util.*; public class E { 
    public static void main(String args[]) { 
    LinkedList< Integer> list=new LinkedList< Integer>(); for(int k=1;k<=10;k++) { 
    list.add(new Integer(k)); } list.remove(5); list.remove(5); Integer m=list.get(5); System.out.println(m.intValue()); } } 

8

2.在下列E类中System.out.println的输出结果是什么?

import java.util.*; public class E { 
    public static void main(String args[]) { 
    Stack<Character> mystack1=new Stack<Character>(), mystack2=new Stack<Character>(); StringBuffer bu=new StringBuffer(); for(char c='A';c<='D';c++) { 
    mystack1.push(new Character(c)); } while(!(mystack1.empty())) { 
    Character temp=mystack1.pop(); mystack2.push(temp); } while(!(mystack2.empty())) { 
    Character temp=mystack2.pop(); bu.append(temp.charValue()); } System.out.println(bu); } } 

ABCD

三、编程题

1.使用堆栈结构输出an的若干项,其中an=2an-1+2an-2,a1=3,a2=8。

import java.util.*; public class E { 
    public static void main(String args[]) { 
    Stack<Integer> stack=new Stack<Integer>(); stack.push(new Integer(3)); stack.push(new Integer(8)); int k=1; while(k<=10) { 
    for(int i=1;i<=2;i++) { 
    Integer F1=stack.pop(); int f1=F1.intValue(); Integer F2=stack.pop(); int f2=F2.intValue(); Integer temp=new Integer(2*f1+2*f2); System.out.println(""+temp.toString()); stack.push(temp); stack.push(F2); k++; } } } } 

2.编写一个程序,将链表中的学生英语成绩单存放到一个树集中,使得按成绩自动排序,并输出排序结果。

import java.util.*; class Student implements Comparable { 
    int english=0; String name; Student(int english,String name) { 
    this.name=name; this.english=english; } public int compareTo(Object b) { 
    Student st=(Student)b; return (this.english-st.english); } } public class E { 
    public static void main(String args[]) { 
    List<Student> list=new LinkedList<Student>(); int score []={ 
   65,76,45,99,77,88,100,79}; String name[]={ 
   "张三","李四","旺季","加戈","为哈","周和","赵李","将集"}; for(int i=0;i<score.length;i++){ 
    list.add(new Student(score[i],name[i])); } Iterator<Student> iter=list.iterator(); TreeSet<Student> mytree=new TreeSet<Student>(); while(iter.hasNext()){ 
    Student stu=iter.next(); mytree.add(stu); } Iterator<Student> te=mytree.iterator(); while(te.hasNext()) { 
    Student stu=te.next(); System.out.println(""+stu.name+" "+stu.english); } } } 

3.有10个U盘,有两个重要的属性:价格和容量。编写一个应用程序,使用TreeMap

类,分别按照价格和容量排序输出10个U盘的详细信息。

import java.util.*; class UDiscKey implements Comparable { 
    double key=0; UDiscKey(double d) { 
    key=d; } public int compareTo(Object b) { 
    UDiscKey disc=(UDiscKey)b; if((this.key-disc.key)==0) return -1; else return (int)((this.key-disc.key)*1000); } } class UDisc{ 
    int amount; double price; UDisc(int m,double e) { 
    amount=m; price=e; } } public class E { 
    public static void main(String args[ ]) { 
    TreeMap<UDiscKey,UDisc> treemap= new TreeMap<UDiscKey,UDisc>(); int amount[]={ 
   1,2,4,8,16}; double price[]={ 
   867,266,390,556}; UDisc UDisc[]=new UDisc[4]; for(int k=0;k<UDisc.length;k++) { 
    UDisc[k]=new UDisc(amount[k],price[k]); } UDiscKey key[]=new UDiscKey[4] ; for(int k=0;k<key.length;k++) { 
    key[k]=new UDiscKey(UDisc[k].amount); } for(int k=0;k<UDisc.length;k++) { 
    treemap.put(key[k],UDisc[k]); } int number=treemap.size(); Collection<UDisc> collection=treemap.values(); Iterator<UDisc> iter=collection.iterator(); while(iter.hasNext()) { 
    UDisc disc=iter.next(); System.out.println(""+disc.amount+"G "+disc.price+"元"); } treemap.clear(); for(int k=0;k<key.length;k++) { 
    key[k]=new UDiscKey(UDisc[k].price); } for(int k=0;k<UDisc.length;k++) { 
    treemap.put(key[k],UDisc[k]); } number=treemap.size(); collection=treemap.values(); iter=collection.iterator(); while(iter.hasNext()) { 
    UDisc disc=iter.next(); System.out.println(""+disc.amount+"G "+disc.price+"元"); } } } 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/205984.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 下午4:44
下一篇 2026年3月19日 下午4:44


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号