达拉草201771010105《面向对象程序设计(java)》第九周学习总结
达拉草201771010105《面向对象程序设计(java)》第九周学习总结
实验九异常、断言与日志
实验时间 2018-10-25
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(); } } |
代码运行结果如下:
Demo1:
Demo2:
调试以后结果如下:
Demo1:
Demo2:
总结:
已检查异常:编译器不要求强制处置的异常,虽然你有可能出现错误,但是我不会在编译的时候检查。
检查异常:就是编译器要求你必须处置的异常。也就是说,你代码还没运行呢,编译器就会检查你的代码,会不会出现异常,要求你对可能出现的异常必须做出相应的处理。
实验2: 导入以下示例程序,测试程序并进行代码注释。
测试程序1:
l 在elipse IDE中编辑、编译、调试运行教材281页7-1,结合程序运行结果理解程序;
l 在程序中相关代码处添加新知识的注释;
l 掌握Throwable类的堆栈跟踪方法;
代码运行结果如下:
总结:
1.Java中的所有异常都是由Throwable类的子类生成的对象,所有的异常类都是Throwable类的子类或子类的子类。Throwable类是Object类的直接子类,Error类和Exception类是Throwable类的两个直接子类。
测试程序2:
l Java语言的异常处理有积极处理方法和消极处理两种方式;
l 下列两个简答程序范例给出了两种异常处理的代码格式。在elipse IDE中编辑、调试运行源程序ExceptionalTest.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 //积极处理方式 2 import java.io.*; 3 import java.io.BufferedReader; 4 import java.io.FileReader; 5 class ExceptionTest { 6 public static void main (String args[]) 7 { 8 9 File fis=new File("身份证号.txt"); 10 try { 11 FileReader fr = new FileReader(fis); 12 BufferedReader br = new BufferedReader(fr); 13 try { 14 String s, s2 = new String(); 15 while ((s = br.readLine()) != null) { 16 s2 += s + "\n "; 17 } 18 br.close(); 19 System.out.println(s2); 20 }catch (IOException e) { 21 e.printStackTrace(); 22 } 23 }catch(FileNotFoundExcption e) 24 { 25 e.printStackTrace(); 26 } 27 } 28 }
1 //消极处理方式 2 3 import java.io.*; 4 class ExceptionTest1 { 5 public static void main (String args[]) throws IOException 6 { 7 File fis=new File("身份证号.txt"); 8 FileReader fr = new FileReader(fis); 9 BufferedReader br = new BufferedReader(fr); 10 11 String s, s2 = new String(); 12 while ((s = br.readLine()) != null) 13 { 14 s2 += s + "\n "; 15 } 16 br.close(); 17 System.out.println(s2); 18 } 19 }
结果如下:
实验3: 编程练习
练习1:
l 编制一个程序,将身份证号.txt 中的信息读入到内存中;
l 按姓名字典序输出人员信息;
l 查询最大年龄的人员信息;
l 查询最小年龄人员信息;
l 输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;
l 查询人员中是否有你的同乡;
l 在以上程序适当位置加入异常捕获代码。
1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 import java.util.ArrayList; 8 import java.util.Arrays; 9 import java.util.Collections; 10 import java.util.Scanner; 11 12 public class Moom{ 13 private static ArrayList<Mest> studentlist; 14 public static void main(String[] args) { 15 studentlist = new ArrayList<>(); 16 Scanner scanner = new Scanner(System.in); 17 File file = new File("D:\\身份证号.txt"); 18 try { 19 FileInputStream fis = new FileInputStream(file); 20 BufferedReader in = new BufferedReader(new InputStreamReader(fis)); 21 String temp = null; 22 while ((temp = in.readLine()) != null) { 23 24 Scanner linescanner = new Scanner(temp); 25 26 linescanner.useDelimiter(" "); 27 String name = linescanner.next(); 28 String number = linescanner.next(); 29 String sex = linescanner.next(); 30 String age = linescanner.next(); 31 String province =linescanner.nextLine(); 32 Mest student = new Mest(); 33 student.setName(name); 34 student.setnumber(number); 35 student.setsex(sex); 36 int a = Integer.parseInt(age); 37 student.setage(a); 38 student.setprovince(province); 39 studentlist.add(student); 40 41 } 42 } catch (FileNotFoundException e) { 43 System.out.println("学生信息文件找不到"); 44 e.printStackTrace(); 45 } catch (IOException e) { 46 System.out.println("学生信息文件读取错误"); 47 e.printStackTrace(); 48 } 49 boolean isTrue = true; 50 while (isTrue) { 51 52 System.out.println("1:字典排序"); 53 System.out.println("2:输出年龄最大和年龄最小的人"); 54 System.out.println("3:寻找老乡"); 55 System.out.println("4:寻找年龄相近的人"); 56 System.out.println("5:退出"); 57 String m = scanner.next(); 58 switch (m) { 59 case "1": 60 Collections.sort(studentlist); 61 System.out.println(studentlist.toString()); 62 break; 63 case "2": 64 int max=0,min=100; 65 int j,k1 = 0,k2=0; 66 for(int i=1;i<studentlist.size();i++) 67 { 68 j=studentlist.get(i).getage(); 69 if(j>max) 70 { 71 max=j; 72 k1=i; 73 } 74 if(j<min) 75 { 76 min=j; 77 k2=i; 78 } 79 80 } 81 System.out.println("年龄最大:"+studentlist.get(k1)); 82 System.out.println("年龄最小:"+studentlist.get(k2)); 83 break; 84 case "3": 85 System.out.println("家庭住址:"); 86 String find = scanner.next(); 87 String place=find.substring(0,3); 88 for (int i = 0; i <studentlist.size(); i++) 89 { 90 if(studentlist.get(i).getprovince().substring(1,4).equals(place)) 91 System.out.println("province"+studentlist.get(i)); 92 } 93 break; 94 95 case "4": 96 System.out.println("年龄:"); 97 int yourage = scanner.nextInt(); 98 int near=agematched(yourage); 99 int value=yourage-studentlist.get(near).getage(); 100 System.out.println(""+studentlist.get(near)); 101 break; 102 case "5": 103 isTrue = false; 104 System.out.println("退出程序!"); 105 break; 106 default: 107 System.out.println("输入错误"); 108 109 } 110 } 111 } 112 public static int agematched(int age) { 113 int j=0,min=53,value=0,k=0; 114 for (int i = 0; i < studentlist.size(); i++) 115 { 116 value=studentlist.get(i).getage()-age; 117 if(value<0) value=-value; 118 if (value<min) 119 { 120 min=value; 121 k=i; 122 } 123 } 124 return k; 125 } 126 127 }
1 public class Mest implements Comparable<Mest> { 2 3 private String name; 4 private String number ; 5 private String sex ; 6 private int age; 7 private String province; 8 9 public String getName() { 10 return name; 11 } 12 public void setName(String name) { 13 this.name = name; 14 } 15 public String getnumber() { 16 return number; 17 } 18 public void setnumber(String number) { 19 this.number = number; 20 } 21 public String getsex() { 22 return sex ; 23 } 24 public void setsex(String sex ) { 25 this.sex =sex ; 26 } 27 public int getage() { 28 29 return age; 30 } 31 public void setage(int age) { 32 33 this.age= age; 34 } 35 36 public String getprovince() { 37 return province; 38 } 39 public void setprovince(String province) { 40 this.province=province ; 41 } 42 43 public int compareTo(Mest o) { 44 return this.name.compareTo(o.getName()); 45 } 46 47 public String toString() { 48 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; 49 } 50 51 }
结果如下:
注:以下实验课后完成
练习2:
l 编写一个计算器类,可以完成加、减、乘、除的操作;
l 利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;
l 将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt;
l 在以上程序适当位置加入异常捕获代码。
1 package MM; 2 3 import java.util.Random; 4 import java.util.Scanner; 5 6 import java.io.FileNotFoundException; 7 8 import java.io.PrintWriter; 9 10 public class Demo{ 11 public static void main(String[] args) 12 { 13 14 MNM counter=new MNM();//与其它类建立联系 15 PrintWriter out=null; 16 try { 17 out=new PrintWriter("D:/text.txt"); 18 19 }catch(FileNotFoundException e) { 20 e.printStackTrace(); 21 } 22 int sum=0; 23 24 for(int i=0;i<10;i++) 25 { 26 int a=new Random().nextInt(100); 27 int b=new Random().nextInt(100); 28 Scanner in=new Scanner(System.in); 29 //in.close(); 30 31 switch((int)(Math.random()*4)) 32 33 { 34 35 case 0: 36 System.out.println( ""+a+"+"+b+"="); 37 38 int M = in.nextInt(); 39 out.println(a+"+"+b+"="+M); 40 if (M == counter.add(a, b)) { 41 sum += 10; 42 System.out.println("答案正确"); 43 } 44 else { 45 System.out.println("答案错误"); 46 } 47 48 break ; 49 case 1: 50 if(a<b) 51 { 52 int temp=a; 53 a=b; 54 b=temp; 55 }//为避免减数比被减数大的情况 56 57 System.out.println(""+a+"-"+b+"="); 58 /*while((a-b)<0) 59 { 60 b = (int) Math.round(Math.random() * 100); 61 62 }*/ 63 int N= in.nextInt(); 64 65 out.println(a+"-"+b+"="+N); 66 if (N == counter.reduce(a, b)) { 67 sum += 10; 68 System.out.println("答案正确"); 69 } 70 else { 71 System.out.println("答案错误"); 72 } 73 74 break ; 75 76 77 78 79 case 2: 80 81 System.out.println(""+a+"*"+b+"="); 82 int c = in.nextInt(); 83 out.println(a+"*"+b+"="+c); 84 if (c == counter.multiply(a, b)) { 85 sum += 10; 86 System.out.println("答案正确"); 87 } 88 else { 89 System.out.println("答案错误"); 90 } 91 break; 92 case 3: 93 94 95 System.out.println(""+a+"/"+b+"="); 96 while(b==0) 97 { b = (int) Math.round(Math.random() * 100); 98 } 99 int c0= in.nextInt(); 100 out.println(a+"/"+b+"="+c0); 101 if (c0 == counter.devision(a, b)) { 102 sum += 10; 103 System.out.println("答案正确"); 104 } 105 else { 106 System.out.println("答案错误"); 107 } 108 109 break; 110 111 112 } 113 } 114 System.out.println("totlescore:"+sum); 115 out.println(sum); 116 117 out.close(); 118 } 119 }
1 package MM; 2 3 public class MNM{ 4 public int add(int a,int b) 5 { 6 return a+b; 7 } 8 public int reduce(int a,int b) 9 { 10 if((a-b)>0) 11 return a-b; 12 else return 0; 13 } 14 public int multiply(int a,int b) 15 { 16 return a*b; 17 } 18 public int devision(int a,int b) 19 { 20 if(b!=0) 21 return a/b; 22 else return 0; 23 24 } 25 }
运行结果如下:
实验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); } } |
l 在elipse下调试程序AssertDemo,结合程序运行结果理解程序;
l 注释语句test1(-5);后重新运行程序,结合程序运行结果理解程序;
l 掌握断言的使用特点及用法。
程序运行结果如下:
注释语句test1(-5);后重新运行程序,结果如下:
总结:
java中使用assert关键字实现断言,java中断言是在运行时候开启。
实验程序2:
l 用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;
l 并掌握Java日志系统的用途及用法。
1 package logging; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.io.*; 6 import java.util.logging.*; 7 import javax.swing.*; 8 9 /** 10 * A modification of the image viewer program that logs various events. 11 * @version 1.03 2015-08-20 12 * @author Cay Horstmann 13 */ 14 public class LoggingImageViewer 15 { 16 public static void main(String[] args) 17 { 18 if (System.getProperty("java.util.logging.config.class") == null 19 && System.getProperty("java.util.logging.config.file") == null) 20 { 21 try 22 { 23 Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL); 24 final int LOG_ROTATION_COUNT = 10; 25 Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT); 26 Logger.getLogger("com.horstmann.corejava").addHandler(handler); 27 } 28 catch (IOException e) 29 { 30 Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE, 31 "Can't create log file handler", e); 32 } 33 } 34 35 EventQueue.invokeLater(() -> 36 { 37 Handler windowHandler = new WindowHandler(); 38 windowHandler.setLevel(Level.ALL); 39 Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler); 40 41 JFrame frame = new ImageViewerFrame(); 42 frame.setTitle("LoggingImageViewer"); 43 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 44 45 Logger.getLogger("com.horstmann.corejava").fine("Showing frame"); 46 frame.setVisible(true); 47 }); 48 } 49 } 50 51 /** 52 * The frame that shows the image. 53 */ 54 class ImageViewerFrame extends JFrame 55 { 56 private static final int DEFAULT_WIDTH = 300; 57 private static final int DEFAULT_HEIGHT = 400; 58 59 private JLabel label; 60 private static Logger logger = Logger.getLogger("com.horstmann.corejava"); 61 62 public ImageViewerFrame() 63 { 64 logger.entering("ImageViewerFrame", "<init>"); 65 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 66 67 // set up menu bar 68 JMenuBar menuBar = new JMenuBar(); 69 setJMenuBar(menuBar); 70 71 JMenu menu = new JMenu("File"); 72 menuBar.add(menu); 73 74 JMenuItem openItem = new JMenuItem("Open"); 75 menu.add(openItem); 76 openItem.addActionListener(new FileOpenListener()); 77 78 JMenuItem exitItem = new JMenuItem("Exit"); 79 menu.add(exitItem); 80 exitItem.addActionListener(new ActionListener() 81 { 82 public void actionPerformed(ActionEvent event) 83 { 84 logger.fine("Exiting."); 85 System.exit(0); 86 } 87 }); 88 89 // use a label to display the images 90 label = new JLabel(); 91 add(label); 92 logger.exiting("ImageViewerFrame", "<init>"); 93 } 94 95 private class FileOpenListener implements ActionListener 96 { 97 public void actionPerformed(ActionEvent event) 98 { 99 logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event); 100 101 // set up file chooser 102 JFileChooser chooser = new JFileChooser(); 103 chooser.setCurrentDirectory(new File(".")); 104 105 // accept all files ending with .gif 106 chooser.setFileFilter(new javax.swing.filechooser.FileFilter() 107 { 108 public boolean accept(File f) 109 { 110 return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory(); 111 } 112 113 public String getDescription() 114 { 115 return "GIF Images"; 116 } 117 }); 118 119 // show file chooser dialog 120 int r = chooser.showOpenDialog(ImageViewerFrame.this); 121 122 // if image file accepted, set it as icon of the label 123 if (r == JFileChooser.APPROVE_OPTION) 124 { 125 String name = chooser.getSelectedFile().getPath(); 126 logger.log(Level.FINE, "Reading file {0}", name); 127 label.setIcon(new ImageIcon(name)); 128 } 129 else logger.fine("File open dialog canceled."); 130 logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed"); 131 } 132 } 133 } 134 135 /** 136 * A handler for displaying log records in a window. 137 */ 138 class WindowHandler extends StreamHandler 139 { 140 private JFrame frame; 141 142 public WindowHandler() 143 { 144 frame = new JFrame(); 145 final JTextArea output = new JTextArea(); 146 output.setEditable(false); 147 frame.setSize(200, 200); 148 frame.add(new JScrollPane(output)); 149 frame.setFocusableWindowState(false); 150 frame.setVisible(true); 151 setOutputStream(new OutputStream() 152 { 153 public void write(int b) 154 { 155 } // not called 156 157 public void write(byte[] b, int off, int len) 158 { 159 output.append(new String(b, off, len)); 160 } 161 }); 162 } 163 164 public void publish(LogRecord record) 165 { 166 if (!frame.isVisible()) return; 167 super.publish(record); 168 flush(); 169 } 170 }
程序运行结果如下:
实验程序3:
用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;
按课件66-77内容练习并掌握Elipse的常用调试技术。
1 package logging; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.io.*; 6 import java.util.logging.*; 7 import javax.swing.*; 8 9 /** 10 * A modification of the image viewer program that logs various events. 11 * @version 1.03 2015-08-20 12 * @author Cay Horstmann 13 */ 14 public class LoggingImageViewer 15 { 16 public static void main(String[] args) 17 { 18 if (System.getProperty("java.util.logging.config.class") == null 19 && System.getProperty("java.util.logging.config.file") == null) 20 { 21 try 22 { 23 Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL); 24 final int LOG_ROTATION_COUNT = 10; 25 Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT); 26 Logger.getLogger("com.horstmann.corejava").addHandler(handler); 27 } 28 catch (IOException e) 29 { 30 Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE, 31 "Can't create log file handler", e); 32 } 33 } 34 35 EventQueue.invokeLater(() -> 36 { 37 Handler windowHandler = new WindowHandler(); 38 windowHandler.setLevel(Level.ALL); 39 Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler); 40 41 JFrame frame = new ImageViewerFrame(); 42 frame.setTitle("LoggingImageViewer"); 43 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 44 45 Logger.getLogger("com.horstmann.corejava").fine("Showing frame"); 46 frame.setVisible(true); 47 }); 48 } 49 } 50 51 /** 52 * The frame that shows the image. 53 */ 54 class ImageViewerFrame extends JFrame 55 { 56 private static final int DEFAULT_WIDTH = 300; 57 private static final int DEFAULT_HEIGHT = 400; 58 59 private JLabel label; 60 private static Logger logger = Logger.getLogger("com.horstmann.corejava"); 61 62 public ImageViewerFrame() 63 { 64 logger.entering("ImageViewerFrame", "<init>"); 65 setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 66 67 // set up menu bar 68 JMenuBar menuBar = new JMenuBar(); 69 setJMenuBar(menuBar); 70 71 JMenu menu = new JMenu("File"); 72 menuBar.add(menu); 73 74 JMenuItem openItem = new JMenuItem("Open"); 75 menu.add(openItem); 76 openItem.addActionListener(new FileOpenListener()); 77 78 JMenuItem exitItem = new JMenuItem("Exit"); 79 menu.add(exitItem); 80 exitItem.addActionListener(new ActionListener() 81 { 82 public void actionPerformed(ActionEvent event) 83 { 84 logger.fine("Exiting."); 85 System.exit(0); 86 } 87 }); 88 89 // use a label to display the images 90 label = new JLabel(); 91 add(label); 92 logger.exiting("ImageViewerFrame", "<init>"); 93 } 94 95 private class FileOpenListener implements ActionListener 96 { 97 public void actionPerformed(ActionEvent event) 98 { 99 logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event); 100 101 // set up file chooser 102 JFileChooser chooser = new JFileChooser(); 103 chooser.setCurrentDirectory(new File(".")); 104 105 // accept all files ending with .gif 106 chooser.setFileFilter(new javax.swing.filechooser.FileFilter() 107 { 108 public boolean accept(File f) 109 { 110 return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory(); 111 } 112 113 public String getDescription() 114 { 115 return "GIF Images"; 116 } 117 }); 118 119 // show file chooser dialog 120 int r = chooser.showOpenDialog(ImageViewerFrame.this); 121 122 // if image file accepted, set it as icon of the label 123 if (r == JFileChooser.APPROVE_OPTION) 124 { 125 String name = chooser.getSelectedFile().getPath(); 126 logger.log(Level.FINE, "Reading file {0}", name); 127 label.setIcon(new ImageIcon(name)); 128 } 129 else logger.fine("File open dialog canceled."); 130 logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed"); 131 } 132 } 133 } 134 135 /** 136 * A handler for displaying log records in a window. 137 */ 138 class WindowHandler extends StreamHandler 139 { 140 private JFrame frame; 141 142 public WindowHandler() 143 { 144 frame = new JFrame(); 145 final JTextArea output = new JTextArea(); 146 output.setEditable(false); 147 frame.setSize(200, 200); 148 frame.add(new JScrollPane(output)); 149 frame.setFocusableWindowState(false); 150 frame.setVisible(true); 151 setOutputStream(new OutputStream() 152 { 153 public void write(int b) 154 { 155 } // not called 156 157 public void write(byte[] b, int off, int len) 158 { 159 output.append(new String(b, off, len)); 160 } 161 }); 162 } 163 164 public void publish(LogRecord record) 165 { 166 if (!frame.isVisible()) return; 167 super.publish(record); 168 flush(); 169 } 170 }
实验总结:
这周我们做的是关于异常,断言与日志的实验,通过这次的实验我知道了已检查异常与检查异常的区别。已检查异常是指编译器不要求强制处置的异常,虽然你有可能出现错误,但是我不会在编译的时候检查。而检查异常就是编译器要求你必须处置的异常。也就是说,你代码还没运行呢,编译器就会检查你的代码,会不会出现异常,要求你对可能出现的异常必须做出相应的处理。