姓名:邹丰蔚
学号:201771010138
实验九 异常、断言与日志
实验时间 2018-10-18
1、实验目的与要求
(1) 掌握java异常处理技术;
(2) 了解断言的用法;
(3) 了解日志的用途;
(4) 掌握程序基础调试技巧;
2、实验内容和步骤
实验1:用命令行与IDE两种环境下编辑调试运行源程序ExceptionDemo1、ExceptionDemo2,结合程序运行结果理解程序,掌握未检查异常和已检查异常的区别。
//异常示例1 ExceptionDemo1: public class ExceptionDemo1 { public static void main(String args[]) { int a = 0; System.out.println(5 / a); } } |
//异常示例2 ExceptionDemo2: import java.io.*;
public class ExceptionDemo2 { public static void main(String args[]) { FileInputStream fis = null; try { fis = new FileInputStream("C:\\Users\\text.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }//JVM自动生成异常对象 int b; try { while((b=fis.read())!=-1) { System.out.print(b); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
实验2: 导入以下示例程序,测试程序并进行代码注释。
测试程序1:
l 在elipse IDE中编辑、编译、调试运行教材281页7-1,结合程序运行结果理解程序;
l 在程序中相关代码处添加新知识的注释;
l 掌握Throwable类的堆栈跟踪方法;
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:
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"); } } |
读入后:
package 异常;
//积极处理方式 import java.io.*; import java.io.BufferedReader; import java.io.FileReader;
class ExceptionTest { public static void main (String args[]) { File fis=new File("C:\\Users\\身份证号.txt"); try{ FileReader fr = new FileReader(fis); BufferedReader br = new BufferedReader(fr); try { String s, s2 = new String(); while ((s = br.readLine()) != null) { s2 += s + "\n "; } br.close(); System.out.println(s2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
实验3: 编程练习
练习1:
l 编制一个程序,将身份证号.txt 中的信息读入到内存中;
l 按姓名字典序输出人员信息;
l 查询最大年龄的人员信息;
l 查询最小年龄人员信息;
l 输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;
l 查询人员中是否有你的同乡;
在以上程序适当位置加入异常捕获代码。
Main: package 身份证;
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 java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.List; import java.util.Scanner;
public class Main{
private static ArrayList<student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("C:\\Users\\身份证号.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String number = linescanner.next();
String sex = linescanner.next();
String year = linescanner.next();
String province =linescanner.nextLine();
student student = student();
student.setname(name);
student.setnumber(number);
student.setsex(sex);
int a = Integer.parseInt(year);
student.setyear(year);
student.setprovince(province);
studentlist.add(student);
}
} catch (FileNotFoundException e) {
System.out.println("学生信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("学生信息文件读取错误");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("1.按姓名字典序输出人员信息:");
System.out.println("2.查询最大年龄的人员信息:");
System.out.println("3.查询最小年龄人员信息:");
System.out.println("4.输入你的年龄,查询身份证号.txt中年龄与你最近人的信息:");
System.out.println("5.查询人员中是否有你的同乡:");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
Collections.sort( studentlist);
System.out.println( studentlist.toString());
break;
case 2:
int MAX=0,MIN=100;int j,k1 = 0,k2=0;
for(int i=1;i< studentlist.size();i++) { j= studentlist.get(i).getyear();
if(j>MAX) { MAX=j; k1=i; }
System.out.println("年龄最大:"+ studentlist.get(k1)); } break;
case 3:
int max=0,min=100;int L,m1 = 0,m2=0;
for(int i=1;i< studentlist.size();i++) { L= studentlist.get(i).getyear(); if(L>max) { max=L; m1=i; } if(L<min) { min=L; m2=i; } } System.out.println("年龄最小:"+ studentlist.get(m2));
break;
case 4: System.out.println("province?");
String find = scanner.next();
String province=find.substring(0,3);
String province2=find.substring(0,3);
for (int i = 0; i < studentlist.size(); i++) { if( studentlist.get(i).getprovince().substring(1,4).equals(province))
System.out.println(studentlist.get(i));
}
break; case 5: System.out.println("年龄:");
int yourage = scanner.nextInt();
int near=yearnear(yourage);
int d_value=yourage-studentlist.get(near).getyear();
System.out.println(""+studentlist.get(near));
/* for (int i = 0; i < Peoplelist.size(); i++) { int p=Personlist.get(i).getage()-yourage; if(p<0) p=-p; if(p==d_value) System.out.println(Peoplelist.get(i)); } */ break; case 6: isTrue = false; System.out.println("退出程序!"); break; default: System.out.println("输入有误"); } } }
private static student student() { // TODO Auto-generated method stub return null; }
public static int yearnear(int year) {
int min=25,d_value=0,k=0; for (int i = 0; i < studentlist.size(); i++) { d_value= studentlist.get(i).getyear()-year; if(d_value<0) d_value=-d_value; if (d_value<min) { min=d_value; k=i; }
} return k;
}
}
|
Student: package 身份证;
public abstract class student implements Comparable<student> {
private String name;
private String number ;
private String sex ;
private String year;
private String province;
public String getname() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getsex() {
return sex ;
}
public void setsex(String sex ) {
this.sex =sex ;
}
public String getyaer() {
return year;
}
public void setyear(String year ) {
this.year=year ;
}
public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
} public int compareTo(student o) { return this.name.compareTo(o.getname());
}
public String toString() { return name+"\t"+sex+"\t"+year+"\t"+number+"\t"+province+"\n"; }
public int getyear() { // TODO Auto-generated method stub return 0; }
public void setname(String name2) { // TODO Auto-generated method stub
} }
|
练习2:
l 编写一个计算器类,可以完成加、减、乘、除的操作;
l 利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;
l 将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt;
l 在以上程序适当位置加入异常捕获代码。
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:断言、日志、程序调试技巧验证实验。
实验程序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 掌握断言的使用特点及用法。
调试后:
package Test;
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:
l 用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;
l 并掌握Java日志系统的用途及用法。
实验程序3:
l 用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;
l 按课件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 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异常处理的一些基础技术;通过调试理解书上的示例程序,再加上老师助、教学长的演示讲解,更好的使我理解这一章的知识。通过实验,我已经掌握了处理异常的方法,并能够在程序中恰当的位置添加try、catch语句了。
原文:https://www.cnblogs.com/siofer/p/9865516.html