马昕璐201771010118 《面对对象程序设计(java)》第九周学习总结
第一部分:理论知识学习部分
异常:在程序的执行过程中所发生的异常事件,它中断指令的正常执行。
Java把程序运行时可能遇到的错误分为两类:
非致命异常:通过某种修正后程序还能继续执行。
致命异常:程序遇到了非常严重的不正常状态,不能简单恢复执行,是致命性错误。
Java中的异常类可分为两大类:;
- Error
Error类层次结构描述了Java 运行时系统的内部错误和资源耗尽错误。应用程序不应该捕获这类异常,也不会抛出这种异常
- Exception
Exception类:重点掌握的异常类。Exception层次结构又分解为两个分支:一个分支派生于RuntimeException;
声明抛出异常在方法声明中用throws子句中来指明。该方法将不对这些异常进行处理,而是声明抛出它们。
Java运行系统从异常生成的代码块开始,寻找相应的异常处理代码,并将异常交给该方法处理,这一过程叫作捕获
–try语句括住可能抛出异常的代码段。
–catch语句指明要捕获的异常及相应的处理代码。
–finally语句指明必须执行的程序块。
断言:是程序的开发和测试阶段用于插入一些代码错误检测语句的工具。
1、assert 条件 或者
2、assert 条件:表达式
断言失败是致命的、不可恢复的错误。 断言检查仅仅用在程序开发和测试阶段
第二部分:实验部分
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();
}
}
检查异常后:
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);
}
}
}
package 异常;
//异常示例2
import java.io.*;
public class ExceptionDemo2 {
public static void main(String args[]) throws Exception
{
FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象
int b;
while((b=fis.read())!=-1)
{
System.out.print(b);
}
fis.close();
}
}
在项目文件夹中添加相应的TXT文件
实验2: 导入以下示例程序,测试程序并进行代码注释。
测试程序1:
1.在elipse IDE中编辑、编译、调试运行教材281页7-1,结合程序运行结果理解程序;
2.在程序中相关代码处添加新知识的注释;
3.掌握Throwable类的堆栈跟踪方法;
7-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();//调用Throwable类的getStackTrace方法,得到StackTraceElement对象的一个数组
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:
1.Java语言的异常处理有积极处理方法和消极处理两种方式;
2.下列两个简答程序范例给出了两种异常处理的代码格式。在elipse IDE中编辑、调试运行源程序ExceptionalTest.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");
}
}
读入内容后:
package 异常;
//积极处理方式
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
class ExceptionTest {
public static void main (String args[])
{
File fis=new File("身份证号.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();
}
}
}
package 异常;
//消极处理方式
import java.io.*;
class ExceptionTest {
public static void main (String args[]) throws IOException
{
File fis=new File("身份证号.txt");
FileReader fr = new FileReader(fis);
BufferedReader br = new BufferedReader(fr);
String s, s2 = new String();
while ((s = br.readLine()) != null) {
s2 += s + "\n ";
}
br.close();
System.out.println(s2);
}
}

实验3: 编程练习
练习1:
1.编制一个程序,将身份证号.txt 中的信息读入到内存中;
2.按姓名字典序输出人员信息;
3.查询最大年龄的人员信息;
4.查询最小年龄人员信息;
5.输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;
6.查询人员中是否有你的同乡;
在以上程序适当位置加入异常捕获代码。
import java.io.File;
import java.io.BufferedReader;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
public class Test {
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("F:\\身份证号.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 age = linescanner.next();
String province = linescanner.nextLine();
Student student = new Student();
student.setName(name);
student.setnumber(number);
student.setsex(sex);
int a = Integer.parseInt(age);
student.setage(a);
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("选择你的操作,输入正确格式的选项");
System.out.println("A.字典排序");
System.out.println("B.输出年龄最大和年龄最小的人");
System.out.println("C.寻找老乡");
System.out.println("D.寻找年龄相近的人");
System.out.println("F.退出");
String m = scanner.next();
switch (m) {
case "A":
Collections.sort(studentlist);
System.out.println(studentlist.toString());
break;
case "B":
int max = 0, min = 100;
int j, k1 = 0, k2 = 0;
for (int i = 1; i < studentlist.size(); i++) {
j = studentlist.get(i).getage();
if (j > max) {
max = j;
k1 = i;
}
if (j < min) {
min = j;
k2 = i;
}
}
System.out.println("年龄最大:" + studentlist.get(k1));
System.out.println("年龄最小:" + studentlist.get(k2));
break;
case "C":
System.out.println("老家?");
String find = scanner.next();
String place = find.substring(0, 3);
for (int i = 0; i < studentlist.size(); i++) {
if (studentlist.get(i).getprovince().substring(1, 4).equals(place))
System.out.println("老乡" + studentlist.get(i));
}
break;
case "D":
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near = agenear(yourage);
int value = yourage - studentlist.get(near).getage();
System.out.println("" + studentlist.get(near));
break;
case "F":
isTrue = false;
System.out.println("退出程序!");
break;
default:
System.out.println("输入有误");
}
}
}
public static int agenear(int age) {
int j = 0, min = 53, value = 0, k = 0;
for (int i = 0; i < studentlist.size(); i++) {
value = studentlist.get(i).getage() - age;
if (value < 0)
value = -value;
if (value < min) {
min = value;
k = i;
}
}
return k;
}
}
public class Student implements Comparable<Student> {
private String name;
private String number ;
private String sex ;
private int age;
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 int getage() {
return age;
}
public void setage(int age) {
// int a = Integer.parseInt(age);
this.age= age;
}
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"+age+"\t"+number+"\t"+province+"\n";
}
}
练习2:
l 编写一个计算器类,可以完成加、减、乘、除的操作;
l 利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;
l 将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt;
l 在以上程序适当位置加入异常捕获代码。
代码:
import java.util.Scanner;
import java.util.Random;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class jisuan {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
yunsuan counter = new yunsuan();
PrintWriter out = null;
try {
out = new PrintWriter("text.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int sum = 0;
System.out.println("随机生成的四则运算类型");
System.out.println("类型1:除法");
System.out.println("类型2:乘法");
System.out.println("类型3:加法");
System.out.println("类型4:减法");
for (int i = 1; i <= 10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int m;
Random rand = new Random();
m = (int) rand.nextInt(4) + 1;
System.out.println("随机生成的四则运算类型:"+m);
switch (m) {
case 1:
System.out.println(i + ": " + a + "/" + b + "=");
while (b == 0) {
b = (int) Math.round(Math.random() * 100);
}
double c0 = in.nextDouble();
out.println(a + "/" + b + "=" + c0);
if (c0 == counter.division(a, b)) {
sum += 10;
System.out.println("right!");
} else {
System.out.println("error!");
}
break;
case 2:
System.out.println(i + ": " + a + "*" + b + "=");
int c = in.nextInt();
out.println(a + "*" + b + "=" + c);
if (c == counter.multiplication(a, b)) {
sum += 10;
System.out.println("right!");
} else {
System.out.println("error!");
}
break;
case 3:
System.out.println(i + ": " + a + "+" + b + "=");
int c1 = in.nextInt();
out.println(a + "+" + b + "=" + c1);
if (c1 == counter.add(a, b)) {
sum += 10;
System.out.println("right!");
} else {
System.out.println("error!");
}
break;
case 4:
System.out.println(i + ": " + a + "-" + b + "=");
int c2 = in.nextInt();
out.println(a + "-" + b + "=" + c2);
if (c2 == counter.reduce(a, b)) {
sum += 10;
System.out.println("right!");
} else {
System.out.println("error!");
}
break;
}
}
System.out.println("成绩" + sum);
out.println("成绩:" + sum);
out.close();
}
}
public class yunsuan {
private int a;
private int b;
public int add(int a, int b) {
return a + b;
}
public int reduce(int a, int b) {
return a - b;
}
public int multiplication (int a,int b){
return a*b;
}
public int division(int a,int b){
if(b!=0)
return a/b;
else
return 0;}
}
运行结果:



实验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 stackTrace;
//断言程序示例
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日志系统的用途及用法。
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();
}
}
LoggingImageViewer
程序运行结果如下:

实验程序3:
l 用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;
l 按课件66-77内容练习并掌握Elipse的常用调试技术。
4. 实验总结:
本周主要讲了异常方面的知识,学习了异常的处理方法,但感觉对内容方面还有不懂的地方,尤其对代码应用方面,仍需研究
马昕璐201771010118 《面对对象程序设计(java)》第九周学习总结的更多相关文章
- 马昕璐 201771010118《面向对象程序设计(java)》第十八周学习总结
实验十八 总复习 实验时间 2018-12-30 1.实验目的与要求 (1) 综合掌握java基本程序结构: (2) 综合掌握java面向对象程序设计特点: (3) 综合掌握java GUI 程序设 ...
- 马昕璐201771010118《面向对象程序设计(java)》第七周学习总结
第一部分:理论知识学习部分 Java用于控制可见性的4个访问权限修饰符: 1.private(只有该类可以访问) 2.protected(该类及其子类的成员可以访问,同一个包中的类也可访问) 3.pu ...
- 马昕璐 201771010118《面向对象程序设计(java)》第六周学习总结
第一部分:理论知识学习部分 1.继承 继承:用已有类来构建新类的一种机制.当定义了一个新类继承了一个类时,这个新类就继承了这个类的方法和域,同时在新类中添加新的方法和域以适应新的情况. 继承是Java ...
- 马昕璐 201771010118《面向对象程序设计(java)》第十五周学习总结
第一部分:理论知识学习部分 JAR文件:将.class文件压缩打包为.jar文件后,使用ZIP压缩格式,GUI界面程序就可以直接双击图标运行. 既可以包含类文件,也可以包含诸如图像和声音这些其它类型的 ...
- 马昕璐 201771010118《面向对象程序设计(java)》第十四周学习总结
第一部分:理论知识学习部分 一.Swing和MVC设计模式 1. MVC模式可应用于Java的GUI组件设计中 2.MVC模式GUI组件设计的唯一的模式,还有很多设计的模式 二.布局管理器 1. 布局 ...
- 马昕璐 201771010118《面向对象程序设计(java)》第十六周学习总结
第一部分:理论知识学习部分 程序:一段静态的代码,应用程序执行的蓝本. 进程:是程序的一次动态执行,它对应了从代码加载.执行至执行完毕的一个完整过程. 多线程:进程执行过程中产生的多条执行线索,比进程 ...
- 20155306 2016-2017-2 《Java程序设计》第九周学习总结
20155306 2016-2017-2 <Java程序设计>第九周学习总结 教材学习内容总结 第十六章 整合数据库 16.1 JDBC入门 Java语言访问数据库的一种规范,是一套API ...
- 20165215 2017-2018-2 《Java程序设计》第九周学习总结
20165215 2017-2018-2 <Java程序设计>第九周学习总结 教材学习内容总结 URL类 URL 类是 java.net 包中的一个重要的类,使用 URL 创建对象的应用程 ...
- 20155312 2016-2017-2 《Java程序设计》第九周学习总结
20155312 2016-2017-2 <Java程序设计>第九周学习总结 课堂内容总结 两个类有公用的东西放在父类里. 面向对象的三要素 封装 继承 多态:用父类声明引用,子类生成对象 ...
- 20155321 2016-2017-2 《Java程序设计》第九周学习总结
20155321 2016-2017-2 <Java程序设计>第九周学习总结 教材学习内容总结 JDBC简介 厂商在实现JDBC驱动程序时,依方式可将驱动程序分为四种类型: JDBC-OD ...
随机推荐
- opencv基础教程
1,基本语法 环境:python3.6.6+numpy+opencv3 安装:没有详细编译,直接pip install opencv-python 矩阵和图片: img=numpy.zeros((3, ...
- oracle参数MEMORY_TARGET太小无法启动的解决过程
环境: windows server datacenter 4G,4x2=8处理器 oracle 11g 错误如下 ORA-: Specified value of MEMORY_TARGET is ...
- Git(1):版本库+工作区+暂存区
参考博客:https://blog.csdn.net/qq_27825451/article/details/69396866
- go语言实现生产者-消费者
前言: 之前在学习操作系统的时候,就知道生产者-消费者,但是概念是模模糊糊的,好像是一直没搞明白. 其实很简单嘛,生产者生产,消费者进行消费,就是如此简单.了解了一下go语言的goroute,感觉实现 ...
- SQL CE 和 SQLite数据库对比测试
于项目需要,在客户端需要做数据存储功能,考虑到部署方便同时满足功能需要的情况下选择了SQLCE 和SQLite两种数据库进行客户端数据存储.当然还有很多其他的方式做本地数据存储,比如本地文件存储.微软 ...
- Windows【端口被占用,杀死想啥的端口】
windows 两步方法 netstat -ano | findstr "8080" taskkill /pid 4136-t -f linux 两步方法 ps -ef | gre ...
- STM32F0使用LL库实现SHT70通讯
在本次项目中,限于空间要求我们选用了STM32F030F4作为控制芯片.这款MCU不但封装紧凑,而且自带的Flash空间也非常有限,所以我们选择了LL库实现.本篇我们将基于LL库采用模拟I2C接口的方 ...
- JS中函数常见的表现形式以及立即执行函数
函数常见的几种表现形式: 1.一般形式(函数声明): 会进行函数的预解释,函数会进行声明和定义,在函数体前面或则后面都可以进行调用. 2.函数表达式(匿名函数): 会进行函数的预解析,函数会进行声明但 ...
- OpenCV-Python:轮廓
啥叫轮廓 轮廓是一系列相连的点组成的曲线,代表了物体的基本外形. 轮廓与边缘很相似,但轮廓是连续的,边缘并不全都连续,其实边缘主要是作为图像的特征使用,比如用边缘特征可以区分脸和手,而轮廓主要用来分析 ...
- [原创]全新IFPGA-Cable----支持Xilinx/Altera/Lattice JTAG和UART
Xilinx 平台:ISE 14.7/Vivado 2014.4+: Lattice 平台:Diamond软件自动识别,免驱动: Altera 平台:安装相关插件,支持: 串 ...