Java2實用教程2(第五版)耿祥義課後習題參考答案

Java2(第5版)最新答案 耿祥義

第1章

一、問答題

1James Gosling

2.需3個步驟:

  1. 用文本編輯器編寫源文件。 
  2. 使用javac編譯源文件,得到字節碼文件。
  3. 使用解釋器運行程序。

3由類所構成,應用程序必須有一個類含有public static void main(String args[])方法,含有該方法的類稱爲應用程序的主類。不一定,但最多有一個public類。

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

5.  java和class

6.  java Bird  

7. 獨行風格(大括號獨佔行)和行尾風格(左大擴號在上一行行尾,右大括號獨佔行)

二、選擇題

1.B。2.D。

三、閱讀程序

1.(a)Person.java。(b)兩個字節碼,分別是Person.class和Xiti.class。(c)得到“NoSuchMethodError”,得到“NoClassDefFoundError: Xiti/class”,得到“您好,很高興認識您 nice to meet you”

第2章

一、問答題

1用來標識類名、變量名、方法名、類型名、數組名、文件名的有效字符序列稱爲標識符。標識符由字母、下劃線、美元符號和數字組成,第一個字符不能是數字。false不是標識符。

2關鍵字就是Java語言中已經被賦予特定意義的一些單詞,不可以把關鍵字作爲名字來用。不是關鍵字。class implements interface enum extends abstract。

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

4.float常量必須用F或f爲後綴。double常量用D或d爲後綴,但允許省略後綴。

5.一維數組名.length。二維數組名.length。

二、選擇題

1.C。2.ADF。3.B。4.BE。5.【代碼2】【代碼3】【代碼4】【代碼5】。6.B。

三、閱讀或調試程序

1.屬於操作題,解答略。

2.屬於操作題,解答略。

3.屬於操作題,解答略。

4.【代碼1】:4。【代碼2】:b[0]=1。

5.【代碼1】:40。【代碼2】:7

四、編寫程序

1.  public class E {

   public static void main(String args[]) {

     System.out.println((int)'你');

     System.out.println((int)'我');  

     System.out.println((int)'他');

   }

}

2.   public class E {

   public static void main (String args[ ]) {

      char cStart='α',cEnd='ω';

      for(char c=cStart;c<=cEnd;c++)

        System.out.print(" "+c);

   }

}

第3章

一、問答題

1boolean

2.不可以

3boolean

4. 不是必須的

5結束while語句的執行

6可以

二、選擇題

1.A。 2.C。 3.C

三、閱讀程序

1你,蘋,甜

2.Jeep好好

3x=-5,y=-1

四、編程序題

1public class Xiti1 {

  public static void main(String args[]) {

double sum=0,a=1;

int i=1;

      while(i<=20) {

          sum=sum+a;

          i++;

          a=a*i;

      }

      System.out.println("sum="+sum);

   }

}

2public 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);

          }

      }

   }

}

3class 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);

   }

}

4public 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);

     }

  }

}

5public 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 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可以不可以。

10.不可以。

11.一個類通過使用new運算符可以創建多個不同的對象,不同的對象的實例變量將被分配不同的內存空間。所有對象的類變量都分配給相同的一處內存,對象共享類變量。

12.代表調用當前方法的對象。不可以。

二、選擇題

1.B。2.D。3.D。4.D。5.CD。6.【代碼1】【代碼4】。7.【代碼4】。

三、閱讀程序

1.【代碼1】:1,【代碼2】:121,【代碼3】:121。

2.sum=-100。

3. 27。

4.【代碼1】:100,【代碼2】:20.0。

5. 上機實習題目,解答略。

6. 上機實習題目,解答略。

四、編程題

CPU.java

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.是。

3.不繼承。

4.聲明與父類同名的成員變量。

5.子類重寫的方法類型和父類的方法的類型一致或者是父類的方法的類型的子類型,重寫的方法的名字、參數個數、參數的類型和父類的方法完全相同。重寫方法的目的是隱藏繼承的方法,子類通過方法的重寫可以把父類的狀態和行爲改變爲自身的狀態和行爲。

6.不可以。

7.Abstract類。

8.上轉型對象不能操作子類新增的成員變量,不能調用子類新增的方法。上轉型對象可以訪問子類繼承或隱藏的成員變量,可以調用子類繼承的方法或子類重寫的實例方法。

9.通過重寫方法。

10.面向抽象編程目的是爲了應對用戶需求的變化,核心是讓類中每種可能的變化對應地交給抽象類的一個子類類去負責,從而讓該類的設計者不去關心具體實現。

二、選擇題

1C。2D。3CD。4D。5B。6B。7D。8B。9A。

三、閱讀程序

1.【代碼1】:15.0。【代碼2】:8.0。

2.【代碼1】:11。【代碼2】:11。

3.【代碼1】:98.0。【代碼2】:12。代碼3】:98.0。【代碼4】:9。

4.【代碼1】:120。【代碼2】:120。代碼3】:-100。

四、編程題

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 Example5_13 {

   public static void main(String args[]) {

      Simulator simulator = new Simulator();

      simulator.playSound(new Dog());

      simulator.playSound(new Cat());

   }

}

習題六(第6章)

一、問答題

1.不能。

2.不能。

3.可以把實現某一接口的類創建的對象的引用賦給該接口聲明的接口變量中。那麼該接口變量就可以調用被類實現的接口中的方法。

4.不可以。

5.可以。

二、選擇題

1D。2AB。3B。

三、閱讀程序

1.【代碼1】:15.0。【代碼2】:8。

2.【代碼1】:18。【代碼2】:15。

四、編程題

Animal.java

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 Example5_13 {

   public static void main(String args[]) {

      Simulator simulator = new Simulator();

      simulator.playSound(new Dog());

      simulator.playSound(new Cat());

   }

}

習題七(第7章)

一、問答題

1.有效。

2.可以。

3.不可以。

4.一定是。

二、選擇題

1C。2C。

三、閱讀程序

1大家好,祝工作順利!

2p是接口變量。

3你好 fine thanks。

4屬於上機實習程序,解答略。

四、編程題

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"是。

2.4和3。

3.false和true。

4.負數。

5.是true。

6.3和-1。

7.會發生NumberFormatException異常。

二、選擇題

1A。2C。3B。4D。5C。

三、閱讀程序

1.【代碼】:蘋果。

2.【代碼】:Love:Game。

3.【代碼1】:15。代碼2】:abc我們。

4.【代碼】:13579。

5.【代碼】:9javaHello。

6屬於上機實習程序,解答略。

7屬於上機實習程序,解答略。

 

四、編程題

1.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.   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.   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.   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.public class E {

      public static void main (String args[ ]) {

        String str = "ab123you你是誰?";

        String regex = "\\D+";

        str = str.replaceAll(regex,"");

        System.out.println(str);

      }

}

6. import java.util.*;

public class E {

   public static void main(String args[]) {

      String cost = "數學87分,物理76分,英語96分";

      Scanner scanner = new Scanner(cost);

      scanner.useDelimiter("[^0123456789.]+");

      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.Frame容器的默認佈局是BorderLayout佈局。

2.不可以。

3.ActionEvent。

4.DocumentEvent。

5.5個。

6.MouseMotionListener。

二、選擇題

1C。2A。3A。4D。5C。

三、編程題

1. 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("[^0123456789.]+");

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

2.FileInputStream按字節讀取文件,FileReader按字符讀取文件。

3.不可以。

4.使用對象流寫入或讀入對象時,要保證對象是序列化的。

5.使用對象流很容易得獲取一個序列化對象的克隆,只需將該對象寫入到對象輸出流,那麼用對象輸入流讀回的對象一定是原對象的一個克隆。

二、選擇題

1C。2B。

三、閱讀程序

1.【代碼1】:51。【代碼2】:0。

2.【代碼1】:3。【代碼2】:abc。代碼3】:1。【代碼4】:dbc。

3上機實習題,解答略。

四、編程題

1. 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.   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){}

   }

}

3.   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("[^0123456789.]+");

            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章)

一、問答題

1.(1)添加數據源,(2)選擇驅動程序,(3)命名數據源名稱。

2.不必使用數據名稱。

3.減輕數據庫內部SQL語句解釋器的負擔。

4.事務由一組SQL語句組成,所謂事務處理是指:應用程序保證事務中的SQL語句要麼全部都執行,要麼一個都不執行。

5.(1)用setAutoCommit()方法關閉自動提交模式,(2)用commit()方法處理事務,(3)用rollback()方法處理事務失敗。

四、編程題

1.  import java.sql.*;

import java.util.*;

public class E {

   public static void main(String args[]) {

     Query query=new Query();

     String dataSource="myData";

     String tableName="goods";

     Scanner read=new Scanner(System.in);

     System.out.print("輸入數據源名:");

     dataSource = read.nextLine();

     System.out.print("輸入表名:");

     tableName = read.nextLine();

     query.setDatasourceName(dataSource);

     query.setTableName(tableName);

     query.setSQL("SELECT * FROM "+tableName);

     query.inputQueryResult();

   }

}

class Query {

   String datasourceName="";        //數據源名

   String tableName="";            //表名

   String SQL;                    //SQL語句

   public Query() {

      try{  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

      }

      catch(ClassNotFoundException e) {

         System.out.print(e);

      }

   }

   public void setDatasourceName(String s) {

      datasourceName = s.trim();

   }

   public void setTableName(String s) {

      tableName = s.trim();

   }

   public void setSQL(String SQL) {

      this.SQL = SQL.trim();

   }

   public void inputQueryResult() {

      Connection con;

      Statement sql;

      ResultSet rs;

      try {

           String uri = "jdbc:odbc:"+datasourceName;

           String id = "";

           String password = "";

           con = DriverManager.getConnection(uri,id,password);

           DatabaseMetaData metadata = con.getMetaData();

           ResultSet rs1 = metadata.getColumns(null,null,tableName,null);

           int 字段個數 = 0;

           while(rs1.next()) {

              字段個數++;

           }

           sql = con.createStatement();

           rs = sql.executeQuery(SQL);

           while(rs.next()) {

             for(int k=1;k<=字段個數;k++) {

                 System.out.print(" "+rs.getString(k)+" ");

             }

             System.out.println("");

           }

           con.close();

       }

       catch(SQLException e) {

           System.out.println("請輸入正確的表名"+e);

       }

   }   

}

2.   import java.sql.*;

import java.util.*;

public class E {

   public static void main(String args[]) {

     Query query = new Query();

     String dataSource = "myData";

     String tableName = "goods";

     query.setDatasourceName(dataSource);

     query.setTableName(tableName);

     String name = "";

     Scanner read=new Scanner(System.in);

     System.out.print("商品名:");

     name = read.nextLine();

     String str="'%["+name+"]%'";

     String SQL = "SELECT * FROM "+tableName+" WHERE name LIKE "+str;

     query.setSQL(SQL);

     System.out.println(tableName+"表中商品名是"+name+"的記錄");

     query.inputQueryResult();

   }

}

class Query {

   String datasourceName="";        //數據源名

   String tableName="";            //表名

   String SQL;                    //SQL語句

   public Query() {

      try{  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

      }

      catch(ClassNotFoundException e) {

         System.out.print(e);

      }

   }

   public void setDatasourceName(String s) {

      datasourceName = s.trim();

   }

   public void setTableName(String s) {

      tableName = s.trim();

   }

   public void setSQL(String SQL) {

      this.SQL = SQL.trim();

   }

   public void inputQueryResult() {

      Connection con;

      Statement sql;

      ResultSet rs;

      try {

           String uri = "jdbc:odbc:"+datasourceName;

           String id = "";

           String password = "";

           con = DriverManager.getConnection(uri,id,password);

           DatabaseMetaData metadata = con.getMetaData();

           ResultSet rs1 = metadata.getColumns(null,null,tableName,null);

           int 字段個數 = 0;

           while(rs1.next()) {

              字段個數++;

           }

           sql = con.createStatement();

           rs = sql.executeQuery(SQL);

           while(rs.next()) {

             for(int k=1;k<=字段個數;k++) {

                 System.out.print(" "+rs.getString(k)+" ");

             }

             System.out.println("");

           }

           con.close();

       }

       catch(SQLException e) {

           System.out.println("請輸入正確的表名"+e);

       }

   }   

}

3.將例子5中的代碼:

String SQL = "SELECT * FROM "+tableName+" ORDER BY name";

更改爲:

String SQL = "SELECT * FROM "+tableName+" ORDER BY madeTime";

可達題目要求。

習題十二(第12章)

一、問答題

14種狀態:新建、運行、中斷和死亡。

2有4種原因的中斷:(1)JVM將CPU資源從當前線程切換給其他線程,使本線程讓出CPU的使用權處於中斷狀態。(2)線程使用CPU資源期間,執行了sleep(int millsecond)方法,使當前線程進入休眠狀態。(3)線程使用CPU資源期間,執行了wait()方法,使得當前線程進入等待狀態。(4)線程使用CPU資源期間,執行某個操作進入阻塞狀態,比如執行讀/寫操作引起阻塞。

3死亡狀態,不能再調用start()方法。

4.新建和死亡狀態。

5.兩種方法:用Thread類或其子類。

6.使用 setPrority(int grade)方法。

7.Java使我們可以創建多個線程,在處理多線程問題時,我們必須注意這樣一個問題:當兩個或多個線程同時訪問同一個變量,並且一個線程需要修改這個變量。我們應對這樣的問題作出處理,否則可能發生混亂。

8當一個線程使用的同步方法中用到某個變量,而此變量又需要其它線程修改後才能符合本線程的需要,那麼可以在同步方法中使用wait()方法。使用wait方法可以中斷方法的執行,使本線程等待,暫時讓出CPU的使用權,並允許其它線程使用這個同步方法。其它線程如果在使用這個同步方法時不需要等待,那麼它使用完這個同步方法的同時,應當用notifyAll()方法通知所有的由於使用這個同步方法而處於等待的線程結束等待。

9.不合理。

10.“吵醒”休眠的線程。一個佔有CPU資源的線程可以讓休眠的線程調用interrupt 方法“吵醒”自己,即導致休眠的線程發生InterruptedException異常,從而結束休眠,重新排隊等待CPU資源。

二、選擇題

1.A。2.A。3.B。

三、閱讀程序

1.屬於上機調試題目,解答略。

2.屬於上機調試題目,解答略。

3.屬於上機調試題目,解答略。

4.屬於上機調試題目,解答略。

5.屬於上機調試題目,解答略。

6.屬於上機調試題目,解答略

7.【代碼】:BA。

8.屬於上機調試題目,解答略

四、編寫程序

1.  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.參照本章例子9

習題十三(第13章)

一、問答題

1.一個URL對象通常包含最基本的三部分信息:協議、地址、資源。

2.URL對象調用InputStream openStream() 方法可以返回一個輸入流,該輸入流指向URL對象所包含的資源。通過該輸入流可以將服務器上的資源信息讀入到客戶端。

3.客戶端的套接字和服務器端的套接字通過輸入、輸出流互相連接後進行通信。

4.使用方法accept(),accept()會返回一個和客戶端Socket對象相連接的Socket對象。accept方法會堵塞線程的繼續執行,直到接收到客戶的呼叫。。

5.域名/IP。

四、編程題

1.  (1)客戶端

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;

            }

      }

   }

}

2.   客戶端Client.java

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;     

           }            

     }

  }

}

3.BroadCastWord.java

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章)

一、問答題

12個參數。

26個參數。

37個參數。

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章)

一、問答題

1LinkedList使用鏈式存儲結構,ArrayList使用順序存儲結構。

2迭代器遍歷在找到集合中的一個對象的同時,也得到待遍歷的後繼對象的引用,因此迭代器可以快速地遍歷集合。

3不是。

4.用HashMap<K,V>來存儲。

二、閱讀程序

1.8。

2.ABCD。

三、編寫程序

1.  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.  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+"元");

      }

    }

}

習題十六(第16章)

1 import java.applet.*;

import java.awt.*;

import java.awt.event.*; 

import javax.swing.*;

public class Xiti2 extends Applet implements ActionListener

{  TextField text1,text2;

   Label label;

   public void init()

   {  text1=new TextField(10);

      text2=new TextField(20);

      Box box1=Box.createHorizontalBox();

      Box box2=Box.createHorizontalBox();

      Box boxV=Box.createVerticalBox();

      box1.add(new Label("輸入一個數回車確定:"));

      box1.add(text1);

      label=new Label("數的平方:");

      box2.add(label);

      box2.add(text2);

      boxV.add(box1);

      boxV.add(box2);

      add(boxV);

      text2.setEditable(false);

      text1.addActionListener(this);

   }

   public void actionPerformed(ActionEvent e)

   {  String number=e.getActionCommand();

      try{ double n=Double.parseDouble(number);

           double m=n*n;

           label.setText(n+"的平方:");

           text2.setText(""+m);

           text1.setText("");

           validate();

         }

      catch(NumberFormatException exp)

         {  text2.setText(""+exp);

         }

   }

}

2 import java.applet.*;

import java.awt.*;

public class Rect extends Applet {

   int w,h;

   public void init() {

      String s1=getParameter("width");  //從html得到"width"的值。

      String s2=getParameter("height");  //從html得到"height"的值。

      w=Integer.parseInt(s1);

      h=Integer.parseInt(s2);

   }

   public void paint(Graphics g) {

      g.drawRect(10,10,w,h);

   }

}

/*<applet code= Rect.class width=280 height=500>

     <Param name="width"  value ="150">

     <Param name="height"  value ="175">

</applet>*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章