《面向对象程序设计(java)》第十周学习总结

201871010115     马北《面向对象程序设计(java)》第十周学习总结

项目 内容
这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/
这个作业的要求在哪里  https://www.cnblogs.com/nwnu-daizh/p/11778090.html
作业学习目标  

1.掌握java异常处理技术;

2.了解断言的用法;

3.了解日志的用途;

4.掌握程序基础调试技巧。

 

 

 

 

 

 

 

 

 

 

 

第一部分:总结第七章理论知识

处理错误。

  错误类型:1)用户输入错误;2)设备错误;3)物理限制;4)代码错误

  1.异常:在程序的执行过程中所发生的异常事件,它中断指令的正常执行。异常对象都是派生于Throwable类的一个实例。

    所有异常类都是由Throwable继承而来,在下一层分解为两个支:Error(致命错误)和Exception(非致命错误)。

    设计java程序时,关注Exception层次结构。Exception层次结构又分解为两个分支:一个分支派生于RuntimeException;另一个分支包含其他异常。RuntimeException为运行时异常类,一般是程序错

    误产生。

    派生于RuntimeException的异常包含下面几种情况:

  1)错误的类型转换

  2)数组访问越界

   3)访问空指针

    Java将派生于Error类或RuntimeException类的所有异常称为未检查异常,编译器允许不对它们做出异常处理。

  2.抛出异常:声明抛出异常在方法声明中用throws子句中来指明。

    1)throws子句可以同时指明多个异常,说明该方法将不对这些异常进行处理,而是声明抛出它们。

    2)一个方法必须声明该方法所有可能抛出的已检查异常,而未检查异常要么不可控制(Error),要么应该避免发生(RuntimeException)。如果方法没有声明所有可能发生的已检查异常,编译器会

      给出一个错误消息。

    3)抛出异常对象通过throw语句来实现。

  3.创建异常类。

    自定义异常类:定义一个派生于Exception的直接或间接子类。如一个派生于IOException的类。

  4.捕获异常:

    1)捕获异常的第一步是用try{}子句选定捕获异常的代码范围,由try所限定的代码块中的语句在执行过程中可能会自动生成异常对象并抛出。

    2)catch子句:catch块是对异常对象进行处理的代码;

      a.每个try代码块可以伴随一个或多个catch语句,用于处理try代码块中所生成的各类异常事件;

      b.catch语句只需要一个形式参数指明它所能捕获的异常类对象,这个异常类必须是Throwable的子类,运行时系统通过参数值把被抛出的异常对象传递给catch块;

      c.catch块可以通过异常对象调用类Throwa。

      getMessage:用来得到有关异常事件的信息;

      printStackTrace:用来跟踪异常事件发生时执行堆栈的内容。

  5.堆栈跟踪:程序执行中一个方法调用过程的列表,它包含了程序执行过程中方法调用的特定位置。

  6.程序编码时异常处理的两种方式:

    1)积极处理方式:确切知道如何处理的异常应该捕获;

    2)消极处理方式:不知道如何去处理的异常声明抛出。

第二部分:实验部分

1、实验目的与要求

  (1) 掌握java异常处理技术;

  (2) 了解断言的用法;

  (3) 了解日志的用途;

  (4) 掌握程序基础调试技巧;

2、实验内容和步骤

实验1:用命令行与IDE两种环境下编辑调试运行源程序ExceptionDemo1、ExceptionDemo2,结合程序运行结果理解程序,掌握未检查异常和已检查异常的区别。

//异常示例1

public class ExceptionDemo1 {

public static void main(String args[]) {

int a = 0;

System.out.println(5 / a);

}

}

//异常示例2

import java.io.*;

 

public class ExceptionDemo2 {

public static void main(String args[])

     {

          FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象

          int b;

          while((b=fis.read())!=-1)

          {

              System.out.print(b);

          }

          fis.close();

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

异常示例1:

实验程序如下:

复制代码
1 package testing;
2 public class ExceptionDemo1 {
3     public static void main(String args[]) {
4         int a = 0;
5         System.out.println(5 / a);
6     }
7 }
复制代码

实验运行结果如下:

 

 

 

 

 因分母为零,程序在运行过程中出现异常。修改后程序如下:

复制代码
 1 package testing;
 2 public class ExceptionDemo1 {
 3     public static void main(String args[]) {
 4         int a = 0;
 5         if(a==0){
 6             System.out.println("程序异常!");
 7         }
 8         else{
 9         System.out.println(5 / a);
10     }
11 }
12 }
复制代码

程序运行结果如下所示:

 

 

 异常示例2

实验程序如下:

复制代码
 1 import java.io.*;
 2 
 3 public class ExceptionDemo2 {
 4     public static void main(String args[]) 
 5      {
 6           FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象
 7           int b;
 8           while((b=fis.read())!=-1)
 9           {
10               System.out.print(b);
11           }
12           fis.close();
13       }
14 }
复制代码

程序中存在文件不能找到的错误。修改方法有两种。

1.用抛出异常方法修改后程序如下:

复制代码
 1 import java.io.*;
 2 
 3 public class ExceptionDemo2 {
 4     public static void main(String args[]) throws IOException 
 5      {
 6           FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象
 7           int b;
 8           while((b=fis.read())!=-1)
 9           {
10               System.out.print(b);
11           }
12           fis.close();
13       }
14 }
复制代码

2.将可能出错代码放入try子句中程序修改后如下:

复制代码
 1 import java.io.*;
 2 
 3 public class ExceptionDemo2 {
 4     public static void main(String args[]) {
 5         FileInputStream fis;
 6         try {
 7             fis = new FileInputStream("text.txt");
 8             // JVM自动生成异常对象
 9             int b;
10             while ((b = fis.read()) != -1) {
11                 System.out.print(b);
12             }
13             fis.close();
14         } catch (Exception e) {
15             // TODO 自动生成的 catch 块
16             e.printStackTrace();
17         }
18     }
19 }
复制代码

text文档中存放如下内容:

 

 

 程序中以字节流输出,程序运行结果如下:

实验2 导入以下示例程序,测试程序并进行代码注释。

测试程序1:

※在elipse IDE中编辑、编译、调试运行教材281页7-1,结合程序运行结果理解程序;

※在程序中相关代码处添加新知识的注释;

※掌握Throwable类的堆栈跟踪方法;

实验程序如下:

 

复制代码
 1 import java.util.*;
 2 
 3 /**
 4  * A program that displays a trace feature of a recursive method call.
 5  * @version 1.01 2004-05-10
 6  * @author Cay Horstmann
 7  */
 8 public class StackTraceTest
 9 {
10    /**
11     * Computes the factorial of a number
12     * @param n a non-negative integer
13     * @return n! = 1 * 2 * . . . * n
14     */
15    public static int factorial(int n)//求阶乘
16    {
17       System.out.println("factorial(" + n + "):");
18       Throwable t = new Throwable();
19       StackTraceElement[] frames = t.getStackTrace();//创建一个表示指定执行点的堆栈跟踪元素,t存放方法调用栈的信息
20       for (StackTraceElement f : frames)
21          System.out.println(f);
22       int r;
23       if (n <= 1) r = 1;
24       else r = n * factorial(n - 1);//计算n个数的阶乘需要调用之前n-1个数的阶乘
25       System.out.println("return " + r);
26       return r;
27    }
28 
29    public static void main(String[] args)
30    {
31       Scanner in = new Scanner(System.in);
32       System.out.print("Enter n: ");
33       int n = in.nextInt();
34       factorial(n);
35    }
36 }
复制代码

 

 

测试程序2:

※Java语言的异常处理有积极处理方法和消极处理两种方式;

※下列两个简单程序范例给出了两种异常处理的代码格式。在elipse IDE中编辑、调试运行源程序ExceptionTest.java,将程序中的text文件更换为身份证号.txt,要求将文件内容读入内容,并在控制台显示;

  掌握两种异常处理技术的特点。

l 掌握两种异常处理技术的特点。

//积极处理方式  

import java.io.*;

 

class ExceptionTest {

public static void main (string args[])

   {

       try{

       FileInputStream fis=new FileInputStream("text.txt");

       }

       catch(FileNotFoundExcption e)

     {   ……  }

……

    }

}

//消极处理方式

 

import java.io.*;

class ExceptionTest {

public static void main (string args[]) throws  FileNotFoundExcption

     {

      FileInputStream fis=new FileInputStream("text.txt");

     }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

程序如下:

1.积极处理方式:

复制代码
 1 import java.io.*;
 2 
 3 class ExceptionTest {
 4     public static void main (string args[])
 5    {
 6        try{
 7            FileInputStream fis=new FileInputStream("text.txt");
 8        }
 9        catch(FileNotFoundExcption e)
10         {   ……  }
11     ……
12     }
13 }
复制代码

读入内容后程序如下:

复制代码
 1 import java.io.*;
 2 
 3 public class desd {
 4     public static void main(String args[]) {
 5         FileInputStream fis;
 6         try {
 7             fis = new FileInputStream("text.txt");
 8             int b;
 9             while ((b = fis.read()) != -1) {
10                 System.out.print(b);
11             }
12             fis.close();
13         } catch (Exception e) {
14             e.printStackTrace();
15         }
16     }
17 }
复制代码

2.消极处理方式:

复制代码
1 import java.io.*;
2 class ExceptionTest {
3     public static void main (string args[]) throws  FileNotFoundExcption
4      {
5          FileInputStream fis=new FileInputStream("text.txt");
6      }
7 }
复制代码

读入内容后程序如下:

复制代码
 1 import java.io.*;
 2 
 3 public class desd {
 4     public static void main(String args[]) throws IOException 
 5      {
 6           FileInputStream fis=new FileInputStream("text.txt");
 7           int b;
 8           while((b=fis.read())!=-1)
 9           {
10               System.out.print(b);
11           }
12           fis.close();
13       }
14 }
复制代码

 text文件如图:

 

 程序运行结果如下:

 

 

实验3: 编程练习

※编写一个计算器类,可以完成加、减、乘、除的操作;

※利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;

※将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt;

※在以上程序适当位置加入异常捕获代码。

思维导图如下:

 

 

实验代码如下:

复制代码
 1 import java.util.Scanner;
 2 import java.io.FileNotFoundException;
 3 import java.io.PrintWriter;
 4 import java.util.Random;
 5 
 6 public class Demo {
 7     public static void main(String[] args) {
 8 
 9         Scanner in = new Scanner(System.in);
10         Number counter = new Number();
11         PrintWriter out = null;
12         try {
13             out = new PrintWriter("text.txt");
14         } catch (FileNotFoundException e) {
15             // TODO Auto-generated catch block
16             e.printStackTrace();
17         }
18         int sum = 0;
19 
20         for (int i = 1; i <= 10; i++) {
21 
22             int a = (int) Math.round(Math.random() * 100);
23             int b = (int) Math.round(Math.random() * 100);
24             int m = (int) Math.round(Math.random() * 3);
25             Random n = new Random();
26 
27             switch (m) {
28             case 0:
29                 System.out.println(i + ": " + a + "/" + b + "=");
30 
31                 while (b == 0) {
32                     b = (int) Math.round(Math.random() * 100);
33                 }
34 
35                 int c = in.nextInt();
36                 out.println(a + "/" + b + "=" + c);
37                 if (c == counter.division(a, b)) {
38                     sum += 10;
39                     System.out.println("恭喜答案正确");
40                 } else {
41                     System.out.println("抱歉,答案错误");
42                 }
43 
44                 break;
45 
46             case 1:
47                 System.out.println(i + ": " + a + "*" + b + "=");
48                 int c1 = in.nextInt();
49                 out.println(a + "*" + b + "=" + c1);
50                 if (c1 == counter.multiplication(a, b)) {
51                     sum += 10;
52                     System.out.println("恭喜答案正确");
53                 } else {
54                     System.out.println("抱歉,答案错误");
55                 }
56                 break;
57             case 2:
58                 System.out.println(i + ": " + a + "+" + b + "=");
59                 int c2 = in.nextInt();
60                 out.println(a + "+" + b + "=" + c2);
61                 if (c2 == counter.add(a, b)) {
62                     sum += 10;
63                     System.out.println("恭喜答案正确");
64                 } else {
65                     System.out.println("抱歉,答案错误");
66                 }
67 
68                 break;
69             case 3:
70                 System.out.println(i + ": " + a + "-" + b + "=");
71                 int c3 = in.nextInt();
72                 out.println(a + "-" + b + "=" + c3);
73                 if (c3 == counter.reduce(a, b)) {
74                     sum += 10;
75                     System.out.println("恭喜答案正确");
76                 } else {
77                     System.out.println("抱歉,答案错误");
78                 }
79                 break;
80 
81             }
82 
83         }
84         System.out.println("成绩" + sum);
85         out.println("成绩:" + sum);
86         out.close();
87 
88     }
89 }
复制代码

 

复制代码
 1 public class Number {
 2     private int a;
 3     private int b;
 4 
 5     public int add(int a, int b) {
 6         return a + b;
 7     }
 8 
 9     public int reduce(int a, int b) {
10         return a - b;
11     }
12 
13     public int multiplication(int a, int b) {
14         return a * b;
15     }
16 
17     public int division(int a, int b) {
18         if (b != 0)
19             return a / b;
20         else
21             return 0;
22     }
23 
24 }
复制代码

程序运行结果如下:

 

 

 

 

实验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);

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

※在elipse下调试程序AssertDemo,结合程序运行结果理解程序;

※注释语句test1(-5);后重新运行程序,结合程序运行结果理解程序;

※掌握断言的使用特点及用法。

实验程序如下:

复制代码
 1 public class AssertDemo {
 2     public static void main(String[] args) {        
 3         test1(-5);
 4         test2(-3);
 5     }
 6     
 7     private static void test1(int a){
 8         assert a > 0;//assert宏的原型定义在<assert.h>中,作用是如果它的条件返回错误,则终止程序执行
 9         System.out.println(a);
10     }
11     private static void test2(int a){
12        assert a > 0 : "这里出错了,a不能小于0";
13         System.out.println(a);
14     }
15 }
复制代码

程序运行结果如下:

 

 注释后程序如下:

复制代码
 1 public class AssertDemo {
 2     public static void main(String[] args) {        
 3        // test1(-5);
 4         test2(-3);
 5     }
 6     
 7     private static void test1(int a){
 8         assert a > 0;//assert宏的原型定义在<assert.h>中,作用是如果它的条件返回错误,则终止程序执行
 9         System.out.println(a);
10     }
11     private static void test2(int a){
12        assert a > 0 : "这里出错了,a不能小于0";
13         System.out.println(a);
14     }
15 }
复制代码

实验运行结果如下:

 

 

实验程序2:

※用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;

※并掌握Java日志系统的用途及用法。

实验程序如下:

复制代码
  1 import java.awt.*;
  2 import java.awt.event.*;
  3 import java.io.*;
  4 import java.util.logging.*;
  5 import javax.swing.*;
  6 
  7 /**
  8  * A modification of the image viewer program that logs various events.
  9  * @version 1.03 2015-08-20
 10  * @author Cay Horstmann
 11  */
 12 public class LoggingImageViewer
 13 {
 14    public static void main(String[] args)
 15    {
 16        //将所有消息记录到应用程序特定的文件中
 17       if (System.getProperty("java.util.logging.config.class") == null
 18             && System.getProperty("java.util.logging.config.file") == null)
 19       {
 20          try//放入可能出错的语句
 21          {
 22             Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);//得到日志记录器
 23             final int LOG_ROTATION_COUNT = 10;
 24             Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
 25             Logger.getLogger("com.horstmann.corejava").addHandler(handler);
 26          }
 27          catch (IOException e)
 28          {
 29             Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
 30                   "Can't create log file handler", e);
 31          }
 32       }
 33 
 34       EventQueue.invokeLater(() ->//使事件派发线程上的可运行对象排队
 35             {
 36                Handler windowHandler = new WindowHandler();
 37                windowHandler.setLevel(Level.ALL);
 38                Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
 39 
 40                JFrame frame = new ImageViewerFrame();
 41                frame.setTitle("LoggingImageViewer");
 42                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 43 
 44                Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
 45                frame.setVisible(true);
 46             });
 47    }
 48 }
 49 
 50 /**
 51  * 显示图像的帧。
 52  */
 53 class ImageViewerFrame extends JFrame
 54 {
 55    private static final int DEFAULT_WIDTH = 300;
 56    private static final int DEFAULT_HEIGHT = 400;   
 57 
 58    private JLabel label;
 59    private static Logger logger = Logger.getLogger("com.horstmann.corejava");
 60 
 61    public ImageViewerFrame()
 62    {
 63       logger.entering("ImageViewerFrame", "<init>");      
 64       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
 65 
 66       //设置菜单栏
 67       JMenuBar menuBar = new JMenuBar();
 68       setJMenuBar(menuBar);
 69 
 70       JMenu menu = new JMenu("File");
 71       menuBar.add(menu);
 72 
 73       JMenuItem openItem = new JMenuItem("Open");
 74       menu.add(openItem);
 75       openItem.addActionListener(new FileOpenListener());
 76 
 77       JMenuItem exitItem = new JMenuItem("Exit");
 78       menu.add(exitItem);
 79       exitItem.addActionListener(new ActionListener()
 80          {
 81             public void actionPerformed(ActionEvent event)
 82             {
 83                logger.fine("Exiting.");
 84                System.exit(0);
 85             }
 86          });
 87 
 88       //使用标签显示图像
 89       label = new JLabel();
 90       add(label);
 91       logger.exiting("ImageViewerFrame", "<init>");
 92    }
 93 
 94    private class FileOpenListener implements ActionListener
 95    {
 96       public void actionPerformed(ActionEvent event)
 97       {
 98          logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);
 99 
100          //设置文件选择器
101          JFileChooser chooser = new JFileChooser();
102          chooser.setCurrentDirectory(new File("."));
103 
104          //接受以.gif结尾的所有文件
105          chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
106             {
107                public boolean accept(File f)
108                {
109                   return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
110                }
111 
112                public String getDescription()
113                {
114                   return "GIF Images";
115                }
116             });
117 
118          //显示文件选择器对话框
119          int r = chooser.showOpenDialog(ImageViewerFrame.this);
120 
121          // 如果图像文件被接受,将其设置为标签的图标
122          if (r == JFileChooser.APPROVE_OPTION)
123          {
124             String name = chooser.getSelectedFile().getPath();
125             logger.log(Level.FINE, "Reading file {0}", name);
126             label.setIcon(new ImageIcon(name));
127          }
128          else logger.fine("File open dialog canceled.");
129          logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
130       }
131    }
132 }
133 
134 /**
135  * 用于在窗口中显示日志记录的处理程序。
136  */
137 class WindowHandler extends StreamHandler//继承
138 {
139    private JFrame frame;
140 
141    public WindowHandler()
142    {
143       frame = new JFrame();
144       final JTextArea output = new JTextArea();
145       output.setEditable(false);
146       frame.setSize(200, 200);
147       frame.add(new JScrollPane(output));
148       frame.setFocusableWindowState(false);
149       frame.setVisible(true);
150       setOutputStream(new OutputStream()
151          {
152             public void write(int b)
153             {
154             } // not called
155 
156             public void write(byte[] b, int off, int len)
157             {
158                output.append(new String(b, off, len));
159             }
160          });
161    }
162 
163    public void publish(LogRecord record)
164    {
165       if (!frame.isVisible()) return;
166       super.publish(record);
167       flush();
168    }
169 }
复制代码

实验运行结果如下:

 

 

实验程序3:

※用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;

※按课件66-77内容练习并掌握Elipse的常用调试技术。

 实验程序如下:

复制代码
  1 import java.awt.*;
  2 import java.awt.event.*;
  3 import java.io.*;
  4 import java.util.logging.*;
  5 import javax.swing.*;
  6 
  7 /**
  8  * A modification of the image viewer program that logs various events.
  9  * @version 1.03 2015-08-20
 10  * @author Cay Horstmann
 11  */
 12 public class LoggingImageViewer
 13 {
 14    public static void main(String[] args)
 15    {
 16        //将所有消息记录到应用程序特定的文件中
 17       if (System.getProperty("java.util.logging.config.class") == null
 18             && System.getProperty("java.util.logging.config.file") == null)
 19       {
 20          try//放入可能出错的语句
 21          {
 22             Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);//得到日志记录器
 23             final int LOG_ROTATION_COUNT = 10;
 24             Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
 25             Logger.getLogger("com.horstmann.corejava").addHandler(handler);
 26          }
 27          catch (IOException e)
 28          {
 29             Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
 30                   "Can't create log file handler", e);
 31          }
 32       }
 33 
 34       EventQueue.invokeLater(() ->//使事件派发线程上的可运行对象排队
 35             {
 36                Handler windowHandler = new WindowHandler();
 37                windowHandler.setLevel(Level.ALL);
 38                Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
 39 
 40                JFrame frame = new ImageViewerFrame();
 41                frame.setTitle("LoggingImageViewer");
 42                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 43 
 44                Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
 45                frame.setVisible(true);
 46             });
 47    }
 48 }
 49 
 50 /**
 51  * 显示图像的帧。
 52  */
 53 class ImageViewerFrame extends JFrame
 54 {
 55    private static final int DEFAULT_WIDTH = 300;
 56    private static final int DEFAULT_HEIGHT = 400;   
 57 
 58    private JLabel label;
 59    private static Logger logger = Logger.getLogger("com.horstmann.corejava");
 60 
 61    public ImageViewerFrame()
 62    {
 63       logger.entering("ImageViewerFrame", "<init>");      
 64       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
 65 
 66       //设置菜单栏
 67       JMenuBar menuBar = new JMenuBar();
 68       setJMenuBar(menuBar);
 69 
 70       JMenu menu = new JMenu("File");
 71       menuBar.add(menu);
 72 
 73       JMenuItem openItem = new JMenuItem("Open");
 74       menu.add(openItem);
 75       openItem.addActionListener(new FileOpenListener());
 76 
 77       JMenuItem exitItem = new JMenuItem("Exit");
 78       menu.add(exitItem);
 79       exitItem.addActionListener(new ActionListener()
 80          {
 81             public void actionPerformed(ActionEvent event)
 82             {
 83                logger.fine("Exiting.");
 84                System.exit(0);
 85             }
 86          });
 87 
 88       //使用标签显示图像
 89       label = new JLabel();
 90       add(label);
 91       logger.exiting("ImageViewerFrame", "<init>");
 92    }
 93 
 94    private class FileOpenListener implements ActionListener
 95    {
 96       public void actionPerformed(ActionEvent event)
 97       {
 98          logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);
 99 
100          //设置文件选择器
101          JFileChooser chooser = new JFileChooser();
102          chooser.setCurrentDirectory(new File("."));
103 
104          //接受以.gif结尾的所有文件
105          chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
106             {
107                public boolean accept(File f)
108                {
109                   return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
110                }
111 
112                public String getDescription()
113                {
114                   return "GIF Images";
115                }
116             });
117 
118          //显示文件选择器对话框
119          int r = chooser.showOpenDialog(ImageViewerFrame.this);
120 
121          // 如果图像文件被接受,将其设置为标签的图标
122          if (r == JFileChooser.APPROVE_OPTION)
123          {
124             String name = chooser.getSelectedFile().getPath();
125             logger.log(Level.FINE, "Reading file {0}", name);
126             label.setIcon(new ImageIcon(name));
127          }
128          else logger.fine("File open dialog canceled.");
129          logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
130       }
131    }
132 }
133 
134 /**
135  * 用于在窗口中显示日志记录的处理程序。
136  */
137 class WindowHandler extends StreamHandler//继承
138 {
139    private JFrame frame;
140 
141    public WindowHandler()
142    {
143       frame = new JFrame();
144       final JTextArea output = new JTextArea();
145       output.setEditable(false);
146       frame.setSize(200, 200);
147       frame.add(new JScrollPane(output));
148       frame.setFocusableWindowState(false);
149       frame.setVisible(true);
150       setOutputStream(new OutputStream()
151          {
152             public void write(int b)
153             {
154             } // not called
155 
156             public void write(byte[] b, int off, int len)
157             {
158                output.append(new String(b, off, len));
159             }
160          });
161    }
162 
163    public void publish(LogRecord record)
164    {
165       if (!frame.isVisible()) return;
166       super.publish(record);
167       flush();
168    }
169 }
复制代码

1)条件断点(有一定条件的断点):在Eclipse Java 编辑区的行头双击就会得到一个断点,代码会运行到此处时停止。

在断点处点击鼠标右键,选择最后一个“Breakpoint Properties”。

2)变量断点:在变量的值初始化,或是变量值改变时可以停止。

3)方法断点:方法断点就是将断点打在方法的入口处。

4)异常断点:当异常发生时,代码会停在异常发生处。

5)重新调试:回退时,请在需要回退的线程方法上点右键,选择“Drop to Frame”。

6)单步执行程序 

7)检查变量

8)改变变量值

三:实验总结。

       这周主要学习了程序产生的异常以及如何解决程序中产生的异常。异常时在程序的执行过程中所发生的非正常事件,它中断指令的正常执行。因此在编写代码时需要及时处理这些错误。对于异常处理,在理论课上听的不是很明白,但在实验课上通过学长演示程序,用抛出异常和将可能出错的语句放入try子句中两种方法,基本理解了异常的产生的原因和解决方法。在运行最后一个实验程序时,对程序不理解,没看懂为什么运行结果是那样的。还有就是老师布置的编程题,我自己能做出来的就是第二种了,虽然不符合老师的要求,但是是自己尽力做的,之后我会好好看网上给出的答案,尽力去理解。

 

posted @ 2019-11-04 20:13  马北  阅读(124)  评论(1编辑  收藏  举报