201871020225- Mu Xingyuan "object-oriented programming (java)" the tenth week learning summary

201871020225- Mu Xingyuan "object-oriented programming ( the Java)," the tenth week learning summary

Bowen text at the beginning:

project

content

This work belongs courses

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

Where this requirement in the job

https://www.cnblogs.com/nwnu-daizh/p/11435127.html

Job learning objectives

(1) master java exception handling technique;

(2) understand the assertion of usage;

(3) understand the purpose of the log;

(4) master the basic program debugging techniques;

Essay Bowen text content:

Part I: Chapter VII summarizes the relevant theoretical knowledge about exception handling

1. processing error

Error type:

(1) a user input errors;

(2) a device error;

(3) physical limitations;

(4) Code Error

2. Abnormal

( 1 ) Definition: unusual event during the execution of the program in what happened, it interrupts the normal execution of instructions. Exception object is derived from an instance of the class Throwable.

( 2 ) Category: All exception classes are from inherited from Throwable, the next layer into two branches: Error (Fatal Error) and Exception (non-fatal errors).

( 3 ) design when java program, attention Exception hierarchy. Exception hierarchy and a decomposition into two branches: a branch derived from a RuntimeException; branches contain other abnormalities. RuntimeException exception class is running, usually produces a program error.

3. derived from RuntimeException exceptions include the following situations:

( 1) Error casts

( 2) out of bounds array access

( 3) Access null pointer

Note: the Java class will send Born Error or RuntimeException class of all exceptions called unchecked exceptions, the compiler does not allow them to make exception handling.

4. throw an exception: in the methods of throw the exception statement to indicate throws clause.

( . 1) at the same time throws clause can specify multiple exceptions, these will not be described which deal with exceptions, but that throw thereof.

( 2) a method must declare all the method may throw checked exceptions, without abnormalities or uncontrollable (Error), or should be avoided (RuntimeException). If the method is not declared all of the possible occurrence of checked exceptions, the compiler will give an error message.

( 3) throws an exception object is achieved by the throw statement.

5. Create exception classes.

Custom exception class: define a derived directly or indirectly subclass of Exception. IOException as a derived class.

6. catch exceptions:

( 1) capture step exception try {} is the selected code range captured clause exception may be generated automatically during the execution of the exception object as defined by the try block of code and throw statement.

( 2) the catch clauses: catch exception code block is a processing object;

   . A try each code block may be accompanied by one or more catch statements for processing different types of exception event try block generated;

 b.catch statement requires only one parameter indicating the abnormal form it can capture an object class, this class exception must be a subclass of Throwable, the value of the system parameter is passed to the catch block exception object is thrown at runtime;

 c.catch block by calling exception object classes Throwa.

   getMessage: used to obtain information on abnormal events;

   printStackTrace: used to track the contents of the execution stack when an abnormal event occurs.

7. Stack trace: a list of program execution process of a method call, it contains a particular location during program execution method call.

8. two ways when a program exception handling code:

( 1) positive approach: know exactly how to handle exceptions should capture;

( 2) a negative approach: do not know how to handle exceptions that throw.

Part II: Experimental part

Experiment 1: The editing and debugging source code ExceptionDemo1 run from the command line and IDE both environments, ExceptionDemo2, the program runs in conjunction with the results of the program to understand and master unchecked exceptions and differences abnormalities checked.

// abnormalities Example 1

public class ExceptionDemo1 {

public static void main(String args[]) {

int a = 0;

System.out.println(5 / a);

}

}

// Example 2 anomalies

import  java.io. *;

 

public class ExceptionDemo2 {

public static void main(String args[])

     {

          FIS = the FileInputStream new new  the FileInputStream ( "text . TXT" ) ; // the JVM exception object generated automatically

          int b;

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

          {

              System.out.print(b);

          }

          fis.close();

      }

}

Specific code as follows:

 //异常示例1

public class ExceptionDemo1 {
     public static void main(String args[]) {
         int a = 0;
         System. out .println(5 / a);
     }
}

Results are as follows:

 

 

Specific code as follows:

//异常示例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();
      }
}

运行结果如下:

 

 

 

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

实验2:测试程序1

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

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

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

具体代码如下:

  1 package stackTrace;
2
3 import java.util.*;
4
5 /**
6  * A program that displays a trace feature of a recursive method call.
7  * @version 1.10 2017-12-14
8  * @author Cay Horstmann
9  */
10 public class StackTraceTest
11 {
12    /**
13     * Computes the factorial of a number
14     * @param n a non-negative integer
15     * @return n! = 1 * 2 * . . . * n
16     */
17    public static int factorial(int n)    //求阶乘
18    {   //调用Throwable类的getStackTrace方法访问栈堆轨迹的文本描述信息
19       System.out.println("factorial(" + n + "):");
20       var walker = StackWalker.getInstance(); //创建对象时调用堆栈的跟踪
21       walker.forEach(System.out::println);    //调用对象walker的foreach循环  
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       try (var in = new Scanner(System.in))
32       {
33          System.out.print("Enter n: ");
34          int n = in.nextInt();
35          factorial(n);
36       }
37    }
38 }

运行结果如下:

 

 

 

实验2:测试程序2

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

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

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

//积极处理方式  

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 import java.io.*;
2
3 class ExceptionTest { 4     public static void main (String args[])
5    {
6        
7        try{
8            FileInputStream fis=new FileInputStream("D://身份证号.txt");
9            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
10            String s = new String();
11            while ((s = in.readLine()) != null) {
12                System.out.println(s);
13            }
14            in.close();
15            fis.close();
16        }
17        catch (FileNotFoundException e) {
18            System.out.println("文件未找到");
19 e.printStackTrace(); 20        } catch (IOException e) {
21            System.out.println("文件读取错误");
22            e.printStackTrace();
23        }
24 }
25 }

消极处理具体代码如下:

 1 import java.io.*;
2
3 public class ExceptionTest { 4     public static void main (String args[]) throws IOException
5    {
6         
7        try{
8            FileInputStream fis=new FileInputStream("D://身份证号.txt");
9            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
10            String s = new String();
11            while ((s = in.readLine()) != null) {
12                System.out.println(s);
13            }
14            in.close();
15            fis.close();
16          
17        }
18        finally {
19         return ;
20        }
21       
22    }
23 }

运行结果如下:

 

 

 

实验3:编程练习

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

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

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

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

具体代码如下:

 

 
package test;
import java.util.Random;
import java.util.Scanner;
public class test{
int sum;
public static void main(String[] args) {
test t=new test();
System.out.println("本次测试共十道题,每题十分,满分一百分");
t.sum=0;
Random r=new Random();
for(int i=0;i<10;i++) {
t.core();
}
System.out.println("考试结束");
System.out.println("你的总分为"+t.sum);
}
private void core() {
Random r=new Random();
int m,n;
m=r.nextInt(11);
n=m%4;
switch(n) {
case 0:
int a ,b,c;
a=r.nextInt(101);
b=r.nextInt(101);
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=sum+10;
}
break;
case 1:
int h,g,f;
h=r.nextInt(101);
g=r.nextInt(101);
System.out.println(h+"-"+"("+g+")"+"= ");
Scanner u=new Scanner(System.in);
f=u.nextInt();
if(f!=h-g)
System.out.println("回答错误");
else {
System.out.println("回答正确");
sum=sum+10;
}
break;
case 2:
int q,w,e;
q=r.nextInt(101);
w=r.nextInt(101);
System.out.println(q+"*"+"("+w+")"+"= ");
  Scanner y=new Scanner(System.in);
e=y.nextInt();
if(e!=q*w)
System.out.println("回答错误");
else {
System.out.println("回答正确");
sum=sum+10;
}
break;
case 3:
double j,k,l;
j=r.nextInt(101);
k=r.nextInt(101);
if(k==0)
k++;
System.out.println(j+"/"+"("+k+")"+"= ");
Scanner z=new Scanner(System.in);
l=z.nextDouble();
if(l!=(j/k)/1.00)
System.out.println("回答错误");
else {
System.out.println("回答正常");
sum=sum+10;
}
break;
}
}
}
 

运行结果如下:

 

 

 

 

 

实验4  断言、日志、程序调试技巧验证实验。

实验4:测试程序1

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

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

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

//断言程序示例

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

    }

}

 

运行结果如下:

 

 

 

 

 打开断言:

 

 

实验4:测试程序2

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

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

具体代码如下:

 

 

运行结果如下:

 

实验4:测试程序3

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

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

具体代码如下:

 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
-

运行结果如下:

 

 

 

第三部分:实验总结

       这一周学习了程序运行过程中产生的异常和处理异常的方法,断言,日志。异常时在程序的执行过程中很常见。因此在编写代码时需要及时处理这些错误。异常的抛出,断言,刚接触时不太能理解,但是通过课后作业和mooc的学习,有了进一步的认识,并且在测试程序和自主编程的练习中体会新知识的应用,知道了一些异常情况的基本处理方式,对于异常有了更深刻的了解,我也将会在后来的实践及学习中多多了解。 

 

Guess you like

Origin www.cnblogs.com/muxingyuan/p/11794929.html