201871010102-常龍龍《面向對象程序設計(java)》第十六週學習總結

項目html

內容java

這個做業屬於哪一個課程編程

https://www.cnblogs.com/nwnu-daizh/數組

這個做業的要求在哪裏多線程

https://www.cnblogs.com/nwnu-daizh/p/12031970.htmlapp

做業學習目標框架

          

            (1) 掌握Java應用程序的打包操做;dom

            (2) 掌握線程概念;ide

            (3) 掌握線程建立的兩種技術。函數

 

第一部分:總結第十二章本週理論知識(25分)

14.1 什麼是線程

1.程序、進程與線程

         ● 程序是一段靜態的代碼,它是應用程序執行的藍本。

         ● 進程是程序的一次動態執行,它對應了從代碼加載、執行至執行完畢的一個完整過程。

         ● 線程是進程執行過程當中產生的多條執行線索。 線程是比進程執行更小的單位。

                

 

2.Java中實現多線程應用有兩種途徑:

  ● 建立Thread類的子類

  ● 在程序中實現Runnable接口

14.1.1 用Thread類的子類建立線程

  只需從Thread類派生出一個子類,在類中必定要實現run()。

  例: class hand extends Thread {

      public void run() {…….}

               }

               class Lefthand extends Thread {

       public void run() {

        for(int i=0;i<=5;i++)

        { System.out.println("You are Students!");

        try{ sleep(500); }

        catch(InterruptedException e) {… }

      }

    }

              class Righthand extends Thread {

       public void run() {

        for(int i=0;i<=5;i++) {

        System.out.println("I am a Teacher!");

        try{ sleep(300); }

        catch(InterruptedException e) {…. } }

      }

               }

而後用該類建立一個對象

      Lefthand left=new Lefthand();

      Righthand right=new Righthand();

用start()方法啓動線程

      left.start();

      right.start();

在程序中實現多線程,關鍵性操做:

      -定義用戶線程操做,即run()方法的實現。

      -在適當的時候啓動線程。

 

public class ThreadTest {

      static Lefthand left;

      static Righthand right;

      public static void main(String[] args) {

      left=new Lefthand();

      right=new Righthand();

      left.start();

      right.start();

    }

}

例:ThreadTest.java 執行結果:

        You are Students!

        I am a Teacher!

        I am a Teacher!

        You are Students!

        I am a Teacher!

        I am a Teacher!

        You are Students!

        I am a Teacher!

        You are Students!

        I am a Teacher!

        You are Students!

        You are Students!

14.1.2 用Runnable()接口建立線程

  ●用Runnable()接口實現多線程時,也必須必須實現run()方法,也需用start()啓動 線程。

  ●用Runnable()接口實現多線程時,經常使用Thread類的構造方法來建立線程對象。

class BallRunnable implements Runnable {

  public void run() {

    try { for (int i = 1; i <= STEPS; i++) {

      ball.move(component.getBounds());

      component.repaint();

      Thread.sleep(DELAY);

        }

    }catch (InterruptedException e) { }

     }

●API:java.lang.Thread

Thread(Runnable r)

Runnable r = new BallRunnable(b, comp);

Thread t = new Thread(r);

建立一個新線程,它調用r的run(), r是一個實現了Runnable接口的類的實例。

● 例14-1 Bounce.java p625

● 例14-4 BounceThread.java p631

14.2 中斷線程

●當線程的run方法執行方法體中最後一條語句後,並經由執行return語句返回時,或者出現了在方法中沒有捕獲的異常時,線程將終止。

●在程序中經常調用interrupt()來終止線程,interrupt()不只可中斷正在運行的線程,並且也能中斷處於blocked狀態的線程,此時interrupt()會拋出一個InterruptedException異常。

●Java提供了幾個用於測試線程是否被中斷的方法。

●void interrupt() 向一個線程發送一箇中斷請求,同時把這個線程的「interrupted」狀態置爲true。 若該線程處於blocked狀態,會拋出InterruptedException。

●static boolean interrupted() 檢測當前線程是否已被中斷,並重置狀態「interrupted」值爲false。

●boolean isInterrupted() 檢測當前線程是否已被中斷,不改變狀態「interrupted」值 。

14.3 線程狀態

線程一共有以下6種狀態:

●New (新建)

●Runnable (可運行)

●Blocked (被阻塞)

●Waiting (等待)

●Timed waiting (計時等待)

●Terminated (被終止)

 

 

14.3.1 新建立線程

●new(新建)

  線程對象剛剛建立,尚未啓動,此時還處於不可運行狀態。

●Thread thread=new Thread(「test」)

  此時線程thread處於新建狀態,但已有了相應的內存空間以及其它資源。

14.3.2 被終止的線程

●Terminated (被終止)

線程被終止的緣由有二:

  一是run()方法中最後一個語句執行完畢,於是天然死亡。

  二是由於一個沒有捕獲的異常終止了run方法,從而意外死亡。

●thread.stop() 能夠調用線程的stop方法殺死一個線程,可是,stop方法已過期,不要在本身的代碼中調用它。

第二部分:實驗部分

實驗1: 導入第13章示例程序,測試程序並進行代碼註釋。

測試程序1

● elipse IDE中調試運行教材585頁程序13-1,結合程序運行結果理解程序;

● 將所生成的JAR文件移到另一個不一樣的目錄中,再運行該歸檔文件,以便確認程序是從JAR文件中,而不是從當前目錄中讀取的資源。

● 掌握建立JAR文件的方法;

代碼以下:

package resource; import java.awt.*; import java.io.*; import java.net.*; import java.util.*; import javax.swing.*; /** * @version 1.41 2015-06-12 * @author Cay Horstmann */
public class ResourceTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new ResourceTestFrame(); frame.setTitle("ResourceTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } /** * 一個加載圖像和文本資源的框架。 */
class ResourceTestFrame extends JFrame { private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 300; public ResourceTestFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); //在找到ResourceTest類的地方查找about.gif文件
      URL aboutURL = getClass().getResource("about.gif"); //將此圖像設置爲框架的圖標
      Image img = new ImageIcon(aboutURL).getImage(); setIconImage(img); JTextArea textArea = new JTextArea(); //getResourceAsStream方法的做用是找到與類位於同一位置的資源,返回一個能夠加載資源的URL或者輸入流
      InputStream stream = getClass().getResourceAsStream("about.txt"); //在讀取文本時使用同一編碼UTF-8
      try (Scanner in = new Scanner(stream, "UTF-8")) { while (in.hasNext()) textArea.append(in.nextLine() + "\n"); } add(textArea); } }

生成jar文件的過程:經過Eclipse中的功能 File->Export->Java->JAR File->選擇須要生成jar文件的包->選擇jar文件存儲位置JAR file->next->next->main class->finish

 

 

  

生成的文件歸檔後使用壓縮包打開:

 

雙擊運行結果以下:

測試程序2:

● 在elipse IDE中調試運行ThreadTest,結合程序運行結果理解程序;

● 掌握線程概念;

● 掌握用Thread的擴展類實現線程的方法;

● 利用Runnable接口改造程序,掌握用Runnable接口建立線程的方法。

代碼以下:

package ThreadTest; class Lefthand extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("You are Students!"); //調用Thread的sleep方法不會建立一個新線程, //sleep是Thread的靜態方法,用於暫停當前線程的活動
               try{ sleep(500); } catch(InterruptedException e) { System.out.println("Lefthand error."); } } } } class Righthand extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("I am a Teacher!"); try{ sleep(300); } catch(InterruptedException e) { System.out.println("Righthand error."); } } } } public class ThreadTest { static Lefthand left; static Righthand right; public static void main(String[] args) { left=new Lefthand(); right=new Righthand(); //同時啓動兩個線程
 left.start(); right.start(); } }

運行結果以下:

 

測試程序3:

● 在Elipse環境下調試教材625頁程序14-一、14-2 14-3,結合程序運行結果理解程序;

● 在Elipse環境下調試教材631頁程序14-4,結合程序運行結果理解程序;

● 對比兩個程序,理解線程的概念和用途;

● 掌握線程建立的兩種技術。

代碼一:

Ball類:

package bounce; import java.awt.geom.*; /** * 在長方形邊緣上移動和反彈的球 * @version 1.33 2007-05-17 * @author Cay Horstmann */
public class Ball { private static final int XSIZE = 15; private static final int YSIZE = 15; private double x = 0; private double y = 0; private double dx = 1; private double dy = 1; /** * 將球移動到下一個位置,若是碰到其中一個邊,則反轉方向 */
   public void move(Rectangle2D bounds) { x += dx; y += dy; //寬度上的最小位置
      if (x < bounds.getMinX()) { x = bounds.getMinX(); dx = -dx; } //寬度上的最大位置
      if (x + XSIZE >= bounds.getMaxX()) { x = bounds.getMaxX() - XSIZE; dx = -dx; } //高度上的最小位置
      if (y < bounds.getMinY()) { y = bounds.getMinY(); dy = -dy; } //寬度上的最大位置
      if (y + YSIZE >= bounds.getMaxY()) { y = bounds.getMaxY() - YSIZE; dy = -dy; } } /** * 獲取球在其當前位置的形狀 */
   public Ellipse2D getShape() { return new Ellipse2D.Double(x, y, XSIZE, YSIZE); } }

BallComponent類:

package bounce; import java.awt.*; import java.util.*; import javax.swing.*; /** * 畫彈力球的部件. * @version 1.34 2012-01-26 * @author Cay Horstmann */
public class BallComponent extends JPanel { private static final int DEFAULT_WIDTH = 450; private static final int DEFAULT_HEIGHT = 350; private java.util.List<Ball> balls = new ArrayList<>(); /** * 增長一個球到組件上。 * @param b the ball to add */
   
   //建立add方法,在add方法中使用球類型集合的add方法向集合中添加球
   public void add(Ball b) { balls.add(b); } //paintComponent方法中有一個Graphics類型的參數,這個參數保留着用於繪製圖像和文本的設置。 //在Java中,全部的繪製都必須使用Graphics對象,其中包含了繪製圖案,圖像和文本的方法。
   public void paintComponent(Graphics g) { super.paintComponent(g); // 使用背景色繪製面板
      Graphics2D g2 = (Graphics2D) g; //獲取每個球的位置和形狀並使用默認顏色進行填充
      for (Ball b : balls) { g2.fill(b.getShape()); } } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } }

Bounce類:

package bounce; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * 顯示動畫彈跳球。 * @version 1.34 2015-06-21 * @author Cay Horstmann */
public class Bounce { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new BounceFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } /** * 有球部件和按鈕的框架。 */
class BounceFrame extends JFrame { private BallComponent comp; public static final int STEPS = 1000; public static final int DELAY = 3; /** * 構造包含用於顯示彈跳球和啓動和關閉按鈕的框架 */
   public BounceFrame() { setTitle("Bounce"); comp = new BallComponent(); add(comp, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); //使用addBuuton方法爲按鈕添加標題,監聽器,而且將按鈕添加至面板中
      addButton(buttonPanel, "Start", event -> addBall()); addButton(buttonPanel, "Close", event -> System.exit(0)); //將按鈕面板添加至框架的南部
 add(buttonPanel, BorderLayout.SOUTH); pack(); } /** *向容器添加按鈕 * @param c the container * @param 爲按鈕設置標題 * @param 爲按鈕設置監聽器 */
   public void addButton(Container c, String title, ActionListener listener) { JButton button = new JButton(title); c.add(button); button.addActionListener(listener); } /** * 在面板中添加一個彈跳球,使其彈跳1000次。 */
   public void addBall() { try { Ball ball = new Ball(); comp.add(ball); for (int i = 1; i <= STEPS; i++) { //這樣設置的話全部球的移動都處於一個線程當中
 ball.move(comp.getBounds()); comp.paint(comp.getGraphics()); Thread.sleep(DELAY); } } //中斷異常
      catch (InterruptedException e) { } } }

運行結果以下:

 

代碼二:

Ball類:

package bounce; import java.awt.geom.*; /** * 在長方形邊緣上移動和反彈的球 * @version 1.33 2007-05-17 * @author Cay Horstmann */
public class Ball { private static final int XSIZE = 15; private static final int YSIZE = 15; private double x = 0; private double y = 0; private double dx = 1; private double dy = 1; /** * 將球移動到下一個位置,若是碰到其中一個邊,則反轉方向 */
   public void move(Rectangle2D bounds) { x += dx; y += dy; //寬度上的最小位置
      if (x < bounds.getMinX()) { x = bounds.getMinX(); dx = -dx; } //寬度上的最大位置
      if (x + XSIZE >= bounds.getMaxX()) { x = bounds.getMaxX() - XSIZE; dx = -dx; } //高度上的最小位置
      if (y < bounds.getMinY()) { y = bounds.getMinY(); dy = -dy; } //寬度上的最大位置
      if (y + YSIZE >= bounds.getMaxY()) { y = bounds.getMaxY() - YSIZE; dy = -dy; } } /** * 獲取球在其當前位置的形狀 */
   public Ellipse2D getShape() { return new Ellipse2D.Double(x, y, XSIZE, YSIZE); } }

BallComponent類:

package bounce; import java.awt.*; import java.util.*; import javax.swing.*; /** * 畫彈力球的部件. * @version 1.34 2012-01-26 * @author Cay Horstmann */
public class BallComponent extends JPanel { private static final int DEFAULT_WIDTH = 450; private static final int DEFAULT_HEIGHT = 350; private java.util.List<Ball> balls = new ArrayList<>(); /** * 增長一個球到組件上。 * @param b the ball to add */
   
   //建立add方法,在add方法中使用球類型集合的add方法向集合中添加球
   public void add(Ball b) { balls.add(b); } //paintComponent方法中有一個Graphics類型的參數,這個參數保留着用於繪製圖像和文本的設置。 //在Java中,全部的繪製都必須使用Graphics對象,其中包含了繪製圖案,圖像和文本的方法。
   public void paintComponent(Graphics g) { super.paintComponent(g); // 使用背景色繪製面板
      Graphics2D g2 = (Graphics2D) g; //獲取每個球的位置和形狀並使用默認顏色進行填充
      for (Ball b : balls) { g2.fill(b.getShape()); } } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } }

BounceThread類:

package bounceThread; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * 顯示動畫彈跳球。 * @version 1.34 2015-06-21 * @author Cay Horstmann */
public class BounceThread { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new BounceFrame(); frame.setTitle("BounceThread"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } /** * 有面板和按鈕的框架。 */
class BounceFrame extends JFrame { private BallComponent comp; public static final int STEPS = 1000; public static final int DELAY = 5; /** * 構造包含用於顯示彈跳球和開始和關閉按鈕的組件的框架 */
   public BounceFrame() { comp = new BallComponent(); add(comp, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); addButton(buttonPanel, "Start", event -> addBall()); addButton(buttonPanel, "Close", event -> System.exit(0)); add(buttonPanel, BorderLayout.SOUTH); pack(); } /** * 添加一個按鈕到框架中. * @param c the container * @param 爲按鈕設置標題 * @param 爲按鈕設置監聽器 */
   public void addButton(Container c, String title, ActionListener listener) { JButton button = new JButton(title); c.add(button); button.addActionListener(listener); } /** * 在畫布上添加一個彈跳球並開始一條線使其彈跳 */
   public void addBall() { Ball ball = new Ball(); comp.add(ball); //將移動球的代碼放置在一個獨立的線程中,運行這段代碼能夠提升彈跳球的相應性能 //實現一個BallRunnable類,而後,將動畫代碼放在run方法中,這樣就即將動畫代碼放在了一個單獨的線程中
      Runnable r = () -> { try { for (int i = 1; i <= STEPS; i++) { ball.move(comp.getBounds()); //調用組件的repaint方法,從新繪製組件
 comp.repaint(); Thread.sleep(DELAY); } } catch (InterruptedException e) { } }; //將Runnable對象做爲入口參數傳入Thread的構造函數,再調用start方法就能夠啓動線程
      Thread t = new Thread(r); t.start(); } }

運行結果以下:

 

 能夠同時運行一個以上線程的程序叫多線程程序。

 

實驗2:結對編程練習:採用GUI界面設計如下程序,並建立程序歸檔文件。

● 設計一個100之內整數小學生四則運算練習程序,由計算機隨機產生10道加減乘除練習題,

學生輸入答案,由程序檢查答案是否正確,每道題正確計10分,錯誤不計分,10道題測試結束後給出測試總分;

● 將程序中測試練習題及學生答題結果輸出到文件,文件名爲test.txt。

1)   程序設計思路簡述;

GUI界面設計思路:

 

      我在框架北部加了一個title(JLabel),在中部加了一個problemPanel面板,problemPanel面板佈局爲10行一列的網格佈局,每一行又是一個contentPanel面板,在contentPanel面板中添加了顯示題號的orderLabel,顯示題目的problemLabel,用於做答的answer,顯示對錯的judgeLabel組件。在框架南部加了一個用於放置按鈕的buttonPanel面板,裏面分別放置makeProblemButton,submitbutton,reset

Button和checkButton。另外還有一個用於顯示txt文本的框架,其中只放置了一個display(JTextArea),最後,我加了一個計時器來限制做答時間(額外補充的)。這樣,就完成了整個小學生四則運算練習程序的GUI頁面佈局。

動做事件設計思路:我爲出題按鈕設置了一個problemAction監聽器,監聽器中又有一個makeOperation方法,用於生成題目,makeOperation方法中使用隨機數產生兩個操做數(第二個操做數過濾掉0),而後再產生一個1-4的隨機數用於設置題目的類型,將生成的題目設置爲problemLabel的標題,再將每一個題的結果存在result數組中。同時爲提交按鈕設置了一個judgeAction監聽器,將answer中輸入的內容與result所存的結果相比較,想同judgeLabel則顯示√,不然顯示×。併爲重置按鈕設置resetAction監聽器,將answer中輸入的內容所有清空,可是不能在提交以後清空。最後爲check按鈕設置checkAction監聽器,將全部信息讀入txt文件,而且建立新框架,在新框架中顯示出最後的信息。在倒計時動做事件中,我使用time類中的schedule方法實現了倒計時的功能,而且在時間剩餘10秒時,字體會放大以用於強調,當時間到0時,會彈出信息對話框,而且當用戶提交時,計時也會中止。

2)   符合編程規範的程序代碼;

 ArithmeticExercisesFrame類:

package demo; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; public class ArithmeticExercisesFrame extends JFrame { private JPanel[] contentPanel=new JPanel[10]; private JLabel[] orderLabel=new JLabel[10]; private JLabel[] problemLabel=new JLabel[10]; private JTextField[] answer=new JTextField[10]; private JLabel[] judge=new JLabel[10]; private JPanel problemPanel; private JButton submitButton; private JButton resetButton; private JPanel buttonPanel; private JLabel title; private JButton makeproblemButton; private int operands1; private int operands2; private int[] result=new int[10]; private JButton checkButton; //private static int i=1;
    private File file=new File("小學生四則運算答案結果"); private JTextArea textarea=new JTextArea(10,20); private JPanel timeLimitPanel; private JLabel sumTime; private JLabel timeLabel; private JLabel timechange; private JLabel s; private Timer time; private JOptionPane message; public ArithmeticExercisesFrame() { setSize(400,630); //添加標題
        JPanel titlePanel=new JPanel(); title = new JLabel("小學生四則運算練習程序"); title.setFont(new Font("宋體",Font.ROMAN_BASELINE,25)); titlePanel.add(title); add(titlePanel,BorderLayout.NORTH); problemPanel = new JPanel(); problemPanel.setLayout(new GridLayout(11,1)); time(); createQuestionBoard(); addQuestionBoard(); makeButtonPanel(); add(problemPanel,BorderLayout.CENTER); } public void time() { timeLimitPanel = new JPanel(); sumTime = new JLabel("總時間:180s"); timeLabel = new JLabel("    倒計時:"); timechange = new JLabel("180"); s = new JLabel("s"); sumTime.setFont(new Font("宋體",Font.ROMAN_BASELINE,20)); sumTime.setForeground(Color.green); timeLabel.setFont(new Font("宋體",Font.ROMAN_BASELINE,20)); timeLabel.setForeground(Color.red); timechange.setFont(new Font("宋體",Font.ROMAN_BASELINE,20)); timechange.setForeground(Color.red); s.setFont(new Font("宋體",Font.ROMAN_BASELINE,20)); s.setForeground(Color.red); timeLimitPanel.add(sumTime); timeLimitPanel.add(timeLabel); timeLimitPanel.add(timechange); timeLimitPanel.add(s); problemPanel.add(timeLimitPanel); } public void createQuestionBoard() { //爲每一行建立一個面板
        for(int i=0;i<10;i++) { contentPanel[i]=new JPanel(); contentPanel[i].setLayout(new FlowLayout(FlowLayout.CENTER,15,0)); } orderLabel = new JLabel[] { new JLabel("第一題:"), new JLabel("第二題:"), new JLabel("第三題:"), new JLabel("第四題:"), new JLabel("第五題:"), new JLabel("第六題:"), new JLabel("第七題:"), new JLabel("第八題:"), new JLabel("第九題:"), new JLabel("第十題:") }; for(int i=0;i<10;i++) { problemLabel[i]=new JLabel("請出題"); answer[i]=new JTextField(8); judge[i]=new JLabel("待定"); judge[i].setFont(new Font("宋體",Font.ROMAN_BASELINE,30)); } } public void addQuestionBoard() { for(int i=0;i<contentPanel.length;i++) { contentPanel[i].add(orderLabel[i]); contentPanel[i].add(problemLabel[i]); contentPanel[i].add(answer[i]); contentPanel[i].add(judge[i]); problemPanel.add(contentPanel[i]); } } public void makeButtonPanel() { buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,0)); makeproblemButton = new JButton("出題"); submitButton=new JButton("提交"); resetButton=new JButton("重置"); checkButton = new JButton("查看"); buttonPanel.add(makeproblemButton); buttonPanel.add(submitButton); buttonPanel.add(resetButton); buttonPanel.add(checkButton); ActionListener problem=new problemAction(); ActionListener countDown=new timeAction(); makeproblemButton.addActionListener(problem); makeproblemButton.addActionListener(countDown); ActionListener judge=new judgeAction(); submitButton.addActionListener(judge); ActionListener reset=new resetAction(); resetButton.addActionListener(reset); ActionListener check=new checkAction(); checkButton.addActionListener(check); add(buttonPanel,BorderLayout.SOUTH); } //產生加減乘除運算的方法
    public void makeOperation() { for(int i=0;i<10;i++) { Random rand=new Random(); int temp; operands1 = rand.nextInt(100) +1; operands2=rand.nextInt(100) +1; while(operands2==0) { operands2=rand.nextInt(100) +1; } int index=rand.nextInt(4) +1; switch(index) { case 1:problemLabel[i].setText(operands1+"+"+operands2); result[i] = operands1+operands2; break; case 2:problemLabel[i].setText(operands1+"-"+operands2); result[i]=operands1-operands2; break; case 3:problemLabel[i].setText(operands1+"*"+operands2); result[i]=operands1*operands2; break; case 4:problemLabel[i].setText(operands1+"/"+operands2); result[i]=operands1/operands2; break; default:System.out.println("error!"); } } } //判斷對錯的方法
    public void judgeProblem() { int score=0; for(int i=0;i<10;i++) { //System.out.println(result[i]);
            int res=Integer.parseInt(answer[i].getText()); //System.out.println(res);
            if(res==result[i]) { judge[i].setText("√"); judge[i].setForeground(Color.green); score+=10; } else { judge[i].setText("×"); judge[i].setForeground(Color.red); score+=0; } textarea.append(orderLabel[i].getText()+" "+problemLabel[i].getText()+"    "+"你的答案:"+answer[i].getText()+"    正確答案:"+result[i]+"\n"); } textarea.append("你的總得分是:"+score+"\n"); } public void savefile() { try { FileWriter fw=new FileWriter(file); //System.out.println(textarea.getText());
 fw.write(textarea.getText()); fw.close(); }catch (FileNotFoundException e) { System.out.println("信息文件找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("信息文件讀取錯誤"); e.printStackTrace(); } } //出題監聽器
    class problemAction implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { makeOperation(); for(int i=0;i<10;i++) { judge[i].setVisible(false); answer[i].setText(null); } } } //判斷正誤監聽器
    class judgeAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { judgeProblem(); savefile(); for(int i=0;i<10;i++) { judge[i].setVisible(true); } time.cancel(); } } //查看結果監聽器
    class checkAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { EventQueue.invokeLater(() -> { var frame = new checkFrame(); frame.setTitle("小學生四則運算答案結果"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } //重置監聽器
    class resetAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { for(int i=0;i<10;i++) { if(!judge[i].isVisible()) { answer[i].setText(null); } } } } //倒計時監聽器
    class timeAction implements ActionListener{ private int i=180; @Override public void actionPerformed(ActionEvent e) { time = new Timer(); time.schedule(new TimerTask() { public void run() { timechange.setText(""+(i--)); if(i<=10) { timechange.setFont(new Font("宋體",Font.ROMAN_BASELINE,30)); } if(i<0) { time.cancel(); message.showMessageDialog(ArithmeticExercisesFrame.this,"同窗,考試時間已結束,請當即中止做答!"); for(int i=0;i<10;i++) { answer[i].setEditable(false); } } } }, 0, 20); } } }

 

 

checkFrame類:

package demo; import java.awt.BorderLayout; import java.awt.Font; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import javax.swing.JFrame; import javax.swing.JTextArea; public class checkFrame extends JFrame { private JTextArea display; private File file; //private static int i=1;
       public checkFrame() { setSize(400,600); display = new JTextArea(10,20); add(display,BorderLayout.CENTER); loadfile(); } public void loadfile() { try { file=new File("小學生四則運算答案結果"); FileInputStream fis = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; display.append("              小學生四則運算答案結果"+"\n"); while((temp=in.readLine())!=null) { display.append(temp+"\n"); } display.setFont(new Font("宋體",Font.ROMAN_BASELINE,15)); in.close(); }catch (FileNotFoundException e) { System.out.println("信息文件找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("信息文件讀取錯誤"); e.printStackTrace(); } } }

ArithmeticExercisesFrameTest類:

package demo; import java.awt.*; import javax.swing.*; /** * @version 1.35 2018-04-10 * @author Cay Horstmann */
public class ArithmeticExercisesFrameTest { public static void main(String[] args) { EventQueue.invokeLater(() -> { var frame = new ArithmeticExercisesFrame(); frame.setTitle("小學生四則運算練習程序"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }

3)   程序運行功能界面截圖;

 

 

 4)   結對過程描述,提供兩人在討論、細化和編程時的結對照片(非擺拍)。

 

5)程序歸檔文件

 

 

 

實驗總結:(15分)

       經過本章的第一個測試程序,我掌握了Java應用程序的打包操做,按個人理解是,若是將Java應用程序打包以後就能夠直接發給其餘人,而那我的就能夠在安裝了java虛擬機的計算機上直接運行此應用程序,大大加大了應用程序的可移植性。經過第三個測試程序,我掌握了線程建立的兩種技術。在結對編程中,一些不懂的知識點我也經過上網查詢慢慢掌握了,最終的編程效果我仍是比較滿意的,可是程序仍是有可提升的餘地,我會繼續努力,將此程序不斷完善,並在此過程當中掌握更多的API以及編程技巧。

相關文章
相關標籤/搜索