实验九异常、断言与日志

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

}

}

更改后的异常1
package aaa;
public class 异常{
public static void main(String args[]) {
int a = 0;
if(a==0)
System.out.println("除数为0");
else
System.out.println(5 / a);
}
}

更改后的异常2

文件名找不到故此出现异常

//异常示例2(找不到文件名)

package aaa;
import java.io.*;

public class b {
public static void main(String args[]) throws IOException //添加抛出申明
{
FileInputStream fis=new FileInputStream("text.txt");//JVM自动生成异常对象
int b;
while((b=fis.read())!=-1)
{
System.out.print(b);
}
fis.close();
}
}

实验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();//构造一个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");

}

}

异常1

package aaa;
//积极处理方式  
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
public 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();
} }
}

异常2

package aaa;
  
//消极处理方式 import java.io.*;
public 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:

l  编制一个程序,将身份证号.txt 中的信息读入到内存中;

l  按姓名字典序输出人员信息;

l  查询最大年龄的人员信息;

l  查询最小年龄人员信息;

l  输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;

l  查询人员中是否有你的同乡;

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

package aaa;

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.Scanner; public class b{
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("身份证号.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("1.字典排序 ");
System.out.println("2.输出年龄最大和年龄最小的人 ");
System.out.println("3.寻找老乡 ");
System.out.println("4.寻找年龄相近的人 ");
System.out.println("5.退出 ");
String m = scanner.next();
switch (m) {
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).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 "3":
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 "4":
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 "5 ":
isTrue = false;
System.out.println("退出程序!");
break;
default:
System.out.println("输入有误"); }
}
}
public static int agenear(int age) {
int j=0,min=53,value=0,ok=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;
ok=i;
}
}
return ok;
}
}
package aaa;

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  在以上程序适当位置加入异常捕获代码。

 package aaa;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner; public class b {
public static void main(String[] args) { Scanner in = new Scanner(System.in);
Student student=new Student();
PrintWriter out = null;
try {
out = new PrintWriter("text.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int sum = 0; for (int i = 1; i <=10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int c= (int) Math.round(Math.random() * 3); switch(c)
{
case 0:
System.out.println(i+": "+a+"/"+b+"="); while(b==0)
{
b = (int) Math.round(Math.random() * 100);
} int C = in.nextInt();
out.println(a+"/"+b+"="+C);
if (C == student.division(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
} break; case 1:
System.out.println(i+": "+a+"*"+b+"=");
int D = in.nextInt();
out.println(a+"*"+b+"="+D);
if (D == student.multiplication(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
break;
case 2:
System.out.println(i+": "+a+"+"+b+"=");
int E = in.nextInt();
out.println(a+"+"+b+"="+E);
if (E == student.add(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
} break ;
case 3:
System.out.println(i+": "+a+"-"+b+"=");
int F = in.nextInt();
out.println(a+"-"+b+"="+F);
if (F == student.reduce(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
break ;
}
}
System.out.println("成绩"+sum);
out.println("成绩:"+sum);
out.close();
}
}
package aaa;
public class Student {
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 duanyan;

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的常用调试技术。

实验总结:

在本周的学习中,掌握了java异常处理的一些基础技术;通过调试测试书上的示例程序,以及老师和助教学长的讲解下使我初步的理解了这一章的知识。课后的自主实验在学长帮助的基础上将其做出来,通过这周的学习初步的对于本章知识有了些许的理解。

 
 
 
好文要顶 关注我 收藏该文

苏浪浪 201771010120 《面向对象程序设计(java)》第9周学习总结的更多相关文章

  1. 201771010134杨其菊《面向对象程序设计java》第九周学习总结

                                                                      第九周学习总结 第一部分:理论知识 异常.断言和调试.日志 1.捕获 ...

  2. 201871010132-张潇潇《面向对象程序设计(java)》第一周学习总结

    面向对象程序设计(Java) 博文正文开头 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cn ...

  3. 扎西平措 201571030332《面向对象程序设计 Java 》第一周学习总结

    <面向对象程序设计(java)>第一周学习总结 正文开头: 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 ...

  4. 杨其菊201771010134《面向对象程序设计Java》第二周学习总结

    第三章 Java基本程序设计结构 第一部分:(理论知识部分) 本章主要学习:基本内容:数据类型:变量:运算符:类型转换,字符串,输入输出,控制流程,大数值以及数组. 1.基本概念: 1)标识符:由字母 ...

  5. 201871010124 王生涛《面向对象程序设计JAVA》第一周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://edu.cnblogs.com/campus/xbsf/ ...

  6. 201871010115——马北《面向对象程序设计JAVA》第二周学习总结

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

  7. 201771010123汪慧和《面向对象程序设计Java》第二周学习总结

    一.理论知识部分 1.标识符由字母.下划线.美元符号和数字组成, 且第一个符号不能为数字.标识符可用作: 类名.变量名.方法名.数组名.文件名等.第二部分:理论知识学习部分 2.关键字就是Java语言 ...

  8. 201777010217-金云馨《面向对象程序设计(Java)》第二周学习总结

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

  9. 201871010132——张潇潇《面向对象程序设计JAVA》第二周学习总结

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

  10. 马凯军201771010116《面向对象与程序设计Java》第九周学习总结

    一.理论知识部分 异常.日志.断言和调试 1.异常:在程序的执行过程中所发生的异常事件,它中断指令的正常执行. 2.Java的异常处理机制可以控制程序从错误产生的位置转移到能够进行错误处理的位置. 3 ...

随机推荐

  1. 怎么break java8 stream的foreach

    目录 简介 使用Spliterator 自定义forEach方法 总结 怎么break java8 stream的foreach 简介 我们通常需要在java stream中遍历处理里面的数据,其中f ...

  2. 【React踩坑记三】React项目报错Can't perform a React state update on an unmounted component

    意思为:我们不能在组件销毁后设置state,防止出现内存泄漏的情况 分析出现问题的原因: 我这里在组件加载完成的钩子函数里调用了一个EventBus的异步方法,如果监听到异步方法,则会更新state中 ...

  3. mac OS 安装破解 Navicat Premium

    Navicat Premium for mac V12.0.24 中文破解版 下载地址 https://www.cnblogs.com/huihuizhang/p/9889780.html 由于新版本 ...

  4. TCP链接的三次握手与四次断开

    一直总觉得三次握手和四次断开,之前老师讲的有问题,经过自己再次琢磨,发现是的,老师讲的没毛病,这次也把自己的理解总结一下,让对这个知识模糊的小伙伴再换种思路去理解 首先看一下TCP三次握手发生了哪些: ...

  5. Process Synchronization-Example 1

    问题描述 把学生和监考老师都看作进程,学生有N人,教师1人.考场门口每次只能进出一个人,进考场原则是先来先进.当N个学生都进入考场后,教师才能发卷子.学生交卷后可以离开考场,教师要等收上来全部卷子并封 ...

  6. 数据库SQL语言从入门到精通--Part 3--SQL语言基础知识

    数据库从入门到精通合集(超详细,学习数据库必看) 一.关系 单一的数据结构----关系 现实世界的实体以及实体间的各种联系均用关系来表示 逻辑结构----二维表 从用户角度,关系模型中数据的逻辑结构是 ...

  7. 最简单,最明了,看了就会的VScode和C++的配置!(Visual Studio Code)

    我看了网上的大佬们配的我是在是看不懂啊?我是一个小白啊?这太难了,这阻挡不了我,想使用这很骚的IDE,于是在不断的摸索下,终于配置成功,小白们也不用慌,这次非常简单.一定可以的. 1.下载 VS Co ...

  8. codeforces 1287A -Angry Students(模拟)

    It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torz ...

  9. 数学--数论--Miller_Rabin判断素数

    ACM常用模板合集 #include<iostream> #include<algorithm> #include<cstring> #include<cst ...

  10. cookie、session 和 token 区别

    1.什么是 cookie cookie 是保存在本地终端的数据.cookie 由服务器生成,发送给浏览器,浏览器把 cookie 以 kv 形式保存到某个目录下的文本文件内,下一次请求同一网站时会把该 ...