1. 程式人生 > >孔維瀅 20171010110《面向對象程序設計(java)》第九周學習總結

孔維瀅 20171010110《面向對象程序設計(java)》第九周學習總結

lower operation gre otf spa handler enter eight des

實驗九

1、實驗目的與要求

(1) 掌握java異常處理技術;

(2) 了解斷言的用法;

(3) 了解日誌的用途;

(4) 掌握程序基礎調試技巧;

2、實驗內容和步驟

實驗1:

package 異常;

//異常示例1
public class ExceptionDemo1 {
    public static void main(String args[]) {
        int a=0;
        if(a==0) {
            System.out.println("除數不能為零!");
        }
        else {
            System.out.println(
5 / a); } } }
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExceptionDemo2 {
    public static void main(String args[]) throws IOException 
     {
          
try { File file = new File("text.txt"); FileInputStream fis = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String b; while((b=in.readLine())!=null) { System.out.print(b); } fis.close(); }
catch (Exception e) { e.printStackTrace(); } } }

實驗2:

測試程序1:

package stackTrace;

import java.util.*;

/**
 * A program that displays a trace feature of a recursive method call.
 * @version 1.01 2004-05-10
 * @author Cay Horstmann
 */
public class StackTraceTest
{
   /**
    * Computes the factorial of a number
    * @param n a non-negative integer
    * @return n! = 1 * 2 * . . . * n
    */
   public static int factorial(int n)
   {
      System.out.println("factorial(" + n + "):");
      Throwable t = new Throwable();
      StackTraceElement[] frames = t.getStackTrace();
      for (StackTraceElement f : frames)
         System.out.println(f);
      int r;
      if (n <= 1) r = 1;
      else r = n * factorial(n - 1);
      System.out.println("return " + r);
      return r;
   }

   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      System.out.print("Enter n: ");
      int n = in.nextInt();
      factorial(n);
   }
}

技術分享圖片

測試程序2:

練習2:

package 計算器;

import java.util.Scanner;
import java.util.Random;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Exam{
    int sum;
    public static void main(String[] args) {
        Exam exam = new Exam();
        exam.sum = 0;
        Random r = new Random ();
        PrintWriter output = null;
        try {
            output = new PrintWriter("E://text.txt");
        } catch (Exception e) {
        }

        for(int i = 0;i<10;i++) {
            exam.score();
        }
        System.out.println("你的總分為:"+exam.sum);
        output.close();
    }
    private void score() {
        Random r = new Random ();
        int m;
        m  = (int) Math.round(Math.random() * 4);
        switch(m) {
        case 0:
            int a,b,c;
            a = r.nextInt() % 100;
            b = r.nextInt() % 100;
            System.out.println(a + "+" + "(" + b + ")=");
            Scanner x = new Scanner(System.in);
            c = x.nextInt();
            if(c != a+b)
                System.out.println("答案錯誤!");
            else {
                System.out.println("答案正確!");
                sum += 10;
            }
            break;
        case 1:
            int o,p,q;
            o = r.nextInt() % 100;
            p = r.nextInt() % 100;
            System.out.println(o + "-" + "(" + p + ")=");
            Scanner y = new Scanner(System.in);
            q = y.nextInt();
            if(q != o-p)
                System.out.println("答案錯誤!");
            else {
                System.out.println("答案正確!");
                sum += 10;
            }
            break;
        case 2:
            int d,e,f;
            d = r.nextInt() % 100;
            e = r.nextInt() % 100;
            System.out.println(d + "*" +"("+ e + ")" + "=");
            Scanner z = new Scanner(System.in);
            f = z.nextInt();
            if(f != d * e)
            System.out.println("答案錯誤!");
            else {
                System.out.println("答案正確!");
                sum += 10;
            }
            break;
        case 3:
            int h,i,j;
            h = r.nextInt() % 100;
            i = r.nextInt() % 100;
            if(i == 0)
                i++;
            System.out.println(h + "/" +"("+ i + ")" + "=");
            Scanner u = new Scanner(System.in);
            j = u.nextInt();
            if(j != h/i)
                System.out.println("答案錯誤!");
            else {
                System.out.println("答案正確!");
                sum += 10;
            }
            break;
        }
    }
}

技術分享圖片

技術分享圖片

實驗4:

實驗程序1:

//斷言程序示例
public class AssertDemo {
    public static void main(String[] args) {        
        //test1(-5);
        test2(-3);
    }
    
    private static void test1(int a){
        assert a > 0;
        System.out.println(a);
    }
    private static void test2(int a){
       assert a > 0 : "something goes wrong here, a cannot be less than 0";
        System.out.println(a);
    }
}

技術分享圖片

技術分享圖片

實驗程序2:

package logging;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.*;
import javax.swing.*;

/**
 * A modification of the image viewer program that logs various events.
 * @version 1.03 2015-08-20
 * @author Cay Horstmann
 */
public class LoggingImageViewer
{
   public static void main(String[] args)
   {
      if (System.getProperty("java.util.logging.config.class") == null
            && System.getProperty("java.util.logging.config.file") == null)
      {
         try
         {
            Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);
            final int LOG_ROTATION_COUNT = 10;
            Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
            Logger.getLogger("com.horstmann.corejava").addHandler(handler);
         }
         catch (IOException e)
         {
            Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
                  "Can‘t create log file handler", e);
         }
      }

      EventQueue.invokeLater(() ->
            {
               Handler windowHandler = new WindowHandler();
               windowHandler.setLevel(Level.ALL);
               Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);

               JFrame frame = new ImageViewerFrame();
               frame.setTitle("LoggingImageViewer");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

               Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
               frame.setVisible(true);
            });
   }
}

/**
 * The frame that shows the image.
 */
class ImageViewerFrame extends JFrame
{
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 400;   

   private JLabel label;
   private static Logger logger = Logger.getLogger("com.horstmann.corejava");

   public ImageViewerFrame()
   {
      logger.entering("ImageViewerFrame", "<init>");      
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // set up menu bar
      JMenuBar menuBar = new JMenuBar();
      setJMenuBar(menuBar);

      JMenu menu = new JMenu("File");
      menuBar.add(menu);

      JMenuItem openItem = new JMenuItem("Open");
      menu.add(openItem);
      openItem.addActionListener(new FileOpenListener());

      JMenuItem exitItem = new JMenuItem("Exit");
      menu.add(exitItem);
      exitItem.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent event)
            {
               logger.fine("Exiting.");
               System.exit(0);
            }
         });

      // use a label to display the images
      label = new JLabel();
      add(label);
      logger.exiting("ImageViewerFrame", "<init>");
   }

   private class FileOpenListener implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);

         // set up file chooser
         JFileChooser chooser = new JFileChooser();
         chooser.setCurrentDirectory(new File("."));

         // accept all files ending with .gif
         chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
            {
               public boolean accept(File f)
               {
                  return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
               }

               public String getDescription()
               {
                  return "GIF Images";
               }
            });

         // show file chooser dialog
         int r = chooser.showOpenDialog(ImageViewerFrame.this);

         // if image file accepted, set it as icon of the label
         if (r == JFileChooser.APPROVE_OPTION)
         {
            String name = chooser.getSelectedFile().getPath();
            logger.log(Level.FINE, "Reading file {0}", name);
            label.setIcon(new ImageIcon(name));
         }
         else logger.fine("File open dialog canceled.");
         logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
      }
   }
}

/**
 * A handler for displaying log records in a window.
 */
class WindowHandler extends StreamHandler
{
   private JFrame frame;

   public WindowHandler()
   {
      frame = new JFrame();
      final JTextArea output = new JTextArea();
      output.setEditable(false);
      frame.setSize(200, 200);
      frame.add(new JScrollPane(output));
      frame.setFocusableWindowState(false);
      frame.setVisible(true);
      setOutputStream(new OutputStream()
         {
            public void write(int b)
            {
            } // not called

            public void write(byte[] b, int off, int len)
            {
               output.append(new String(b, off, len));
            }
         });
   }

   public void publish(LogRecord record)
   {
      if (!frame.isVisible()) return;
      super.publish(record);
      flush();
   }
}

技術分享圖片

技術分享圖片

實驗總結:

通過這一章的學習,我重點學習到了什麽是異常,異常是在程序的執行過程中所發生的異常事件,它中斷指令的正常執行。他分為非致命異常和致命異常。Java中所有的異常類都直接或間接地繼承於 Throwable類。Exception類中的RuntimeException為運行時異常類,一般由程序錯誤產生。派生於Error類或RuntimeException類的所有異常被稱為未檢查異常,編譯器允許不對這些異常進行處理 。捕獲異常:try、catch、finally塊。

Try語句:括住可能拋出異常的代碼段

Catch語句:指明要捕獲的異常及相應的處理代碼

Finally語句:必須執行的程序塊

還有斷言以及日誌和調試,斷言是程序的開發和測試階段用於插入一些代碼錯誤檢測語句的工具。

其次,對於練習二的程序,我還有一點沒有完成,就是沒有將成績單輸出到TXT文件中。

孔維瀅 20171010110《面向對象程序設計(java)》第九周學習總結