关键词:
实验部分
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();
|
修改后:
public class ExceptionDemo1 public static void main(String[] args) int a = 0; if(a==0) System.out.println("除数为零"); else System.out.println(5 / a);
import java.io.*; public class ExceptionDemo2 public static void main(String args[]) FileInputStream fis; try fis = new FileInputStream("text.txt"); int b; while((b=fis.read())!=-1) System.out.print(b); fis.close(); catch (Exception e) // TODO Auto-generated catch block e.printStackTrace();//打印堆栈信息 // System.out.println("Hello."); //JVM自动生成异常对象
实验2: 导入以下示例程序,测试程序并进行代码注释。
测试程序1:
l 在elipse IDE中编辑、编译、调试运行教材281页7-1,结合程序运行结果理解程序;
l 在程序中相关代码处添加新知识的注释;
掌握Throwable类的堆栈跟踪方法;
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();//创建一个表示指定执行点的堆栈跟踪元素,t存放方法调用栈的信息 for (StackTraceElement f : frames) System.out.println(f); int r; if (n <= 1) r = 1; else r = n * factorial(n - 1);//计算n个数的阶乘需要调用之前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,要求将文件内容读入内容,并在控制台显示;
掌握两种异常处理技术的特点。
//积极处理方式 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");
|
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class ExceptionalTest public static void main(String args[]) try FileInputStream fis = new FileInputStream("身份证号.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String a,b = new String(); while ((a = in.readLine()) != null) b += a + " "; in.close(); System.out.println(b); catch (FileNotFoundException e) System.out.println("学生信息文件找不到"); e.printStackTrace(); catch (IOException e) System.out.println("学生信息文件读取错误"); e.printStackTrace();
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class ExceptionalTest public static void main(String[] args) throws IOException FileInputStream fis = new FileInputStream("身份证号.txt"); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String a, b = new String(); while ((a = in.readLine()) != null) b += a+ " "; in.close(); System.out.println(b);
实验3: 编程练习
练习1:
l 编制一个程序,将身份证号.txt 中的信息读入到内存中;
l 按姓名字典序输出人员信息;
l 查询最大年龄的人员信息;
l 查询最小年龄人员信息;
l 输入你的年龄,查询身份证号.txt中年龄与你最近人的姓名、身份证号、年龄、性别和出生地;
l 查询人员中是否有你的同乡;
l 在以上程序适当位置加入异常捕获代码。
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.Scanner; import java.util.Collections;//对集合进行排序、查找、修改等; public class Test private static ArrayList<Citizen> citizenlist; public static void main(String[] args) citizenlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("E:/java/身份证号.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 id = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String birthplace = linescanner.nextLine(); Citizen citizen = new Citizen(); citizen.setName(name); citizen.setId(id); citizen.setSex(sex); // 将字符串转换成10进制数 int ag = Integer.parseInt(age); citizen.setage(ag); citizen.setBirthplace(birthplace); citizenlist.add(citizen); 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.输入你的年龄,查询文件中年龄与你最近人的姓名、身份证号、年龄、性别和出生地"); System.out.println("5.退出"); int nextInt = scanner.nextInt(); switch (nextInt) case 1: Collections.sort(citizenlist); System.out.println(citizenlist.toString()); break; case 2: int max = 0, min = 100; int m, k1 = 0, k2 = 0; for (int i = 1; i < citizenlist.size(); i++) m = citizenlist.get(i).getage(); if (m > max) max = m; k1 = i; if (m < min) min = m; k2 = i; System.out.println("年龄最大:" + citizenlist.get(k1)); System.out.println("年龄最小:" + citizenlist.get(k2)); break; case 3: System.out.println("出生地:"); String find = scanner.next(); String place = find.substring(0, 3); for (int i = 0; i < citizenlist.size(); i++) if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place)) System.out.println("出生地" + citizenlist.get(i)); break; case 4: System.out.println("年龄:"); int yourage = scanner.nextInt(); int near = peer(yourage); int j = yourage - citizenlist.get(near).getage(); System.out.println("" + citizenlist.get(near)); break; case 5: isTrue = false; System.out.println("程序已退出!"); break; default: System.out.println("输入有误"); public static int peer(int age) int flag = 0; int min = 53, j = 0; for (int i = 0; i < citizenlist.size(); i++) j = citizenlist.get(i).getage() - age; if (j < 0) j = -j; if (j < min) min = j; flag = i; return flag;
public class Citizen implements Comparable<Citizen> private String name; private String id; private String sex; private int age; private String birthplace; public String getName() return name; public void setName(String name) this.name = name; public String getId() return id; public void setId(String id) this.id = id; public String getSex() return sex; public void setSex(String sex) this.sex = sex; public int getage() return age; public void setage(int age) this.age = age; public String getBirthplace() return birthplace; public void setBirthplace(String birthplace) this.birthplace = birthplace; public int compareTo(Citizen other) return this.name.compareTo(other.getName()); public String toString() return name + " " + sex + " " + age + " " + id + " " + birthplace + " ";
练习2:
l 编写一个计算器类,可以完成加、减、乘、除的操作;
l 利用计算机类,设计一个小学生100以内数的四则运算练习程序,由计算机随机产生10道加减乘除练习题,学生输入答案,由程序检查答案是否正确,每道题正确计10分,错误不计分,10道题测试结束后给出测试总分;
l 将程序中测试练习题及学生答题结果输出到文件,文件名为test.txt;
l 在以上程序适当位置加入异常捕获代码。
import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class calculator public static void main(String[] args) Scanner in = new Scanner(System.in); PrintWriter out = null; try out = new PrintWriter("test.txt"); int sum = 0; for (int i = 0; i < 10; i++) int a = (int) Math.round(Math.random() * 10); int b = (int) Math.round(Math.random() * 10); int menu = (int) Math.round(Math.random() * 3); switch (menu) case 1: System.out.println(a + "+" + b + "="); int c1 = in.nextInt(); if (c1 == (a + b)) sum += 10; System.out.println("恭喜答案正确"); else System.out.println("抱歉,答案错误"); break; case 2: System.out.println(a + "-" + b + "="); int c2 = in.nextInt(); if (c2 == (a - b)) sum += 10; System.out.println("恭喜答案正确"); else System.out.println("抱歉,答案错误"); break; case 3: System.out.println(a + "*" + b + "="); int c = in.nextInt(); if (c == a * b) sum += 10; System.out.println("恭喜答案正确"); else System.out.println("抱歉,答案错误"); break; case 4: if (b == 0) System.out.println("除数为零"); else System.out.println(a + "/" + b + "="); int c4 = in.nextInt(); if (c4 == a / b) sum += 10; System.out.println("恭喜答案正确"); else System.out.println("抱歉,答案错误"); break; System.out.println("你的得分为" + sum); out.println("你的得分为" + sum); out.close(); catch (FileNotFoundException e) e.printStackTrace();
实验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);后重新运行程序,结合程序运行结果理解程序;
掌握断言的使用特点及用法。
实验程序2:
l 用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;
并掌握Java日志系统的用途及用法。
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); ); /** * 显示图像的帧。 */ 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); //设置菜单栏 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); ); //使用标签显示图像 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); //设置文件选择器 JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); //接受以.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"; ); //显示文件选择器对话框 int r = chooser.showOpenDialog(ImageViewerFrame.this); // 如果图像文件被接受,将其设置为标签的图标 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"); /** * 用于在窗口中显示日志记录的处理程序。 */ 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();
实验程序3:
l 用JDK命令调试运行教材298页-300页程序7-2,结合程序运行结果理解程序;
l 按课件66-77内容练习并掌握Elipse的常用调试技术。
1)条件断点(有一定条件的断点):在Eclipse Java 编辑区的行头双击就会得到一个断点,代码会运行到此处时停止。
在断点处点击鼠标右键,选择最后一个“Breakpoint Properties”。
2)变量断点:在变量的值初始化,或是变量值改变时可以停止。
3)方法断点:方法断点就是将断点打在方法的入口处。
4)异常断点:当异常发生时,代码会停在异常发生处。
5)重新调试:回退时,请在需要回退的线程方法上点右键,选择“Drop to Frame”。
6)单步执行程序
7)检查变量
8)改变变量值
实验总结:
通过本周的学习,我对于Java程序运行中出现的异常,断言有了初步的理解。但是在实验过程中,我发现我需要多加练习,加深理解。课下我会多加练习,对于之前所学的知识多加回顾,查漏补缺。
周强201771010141《面向对象与程序设计java》第十四周学习总结
实验十四 Swing图形界面组件实验时间20178-11-29 理论部分:不使用布局管理器有时候可能不想使用任何布局管理器,而只是想把组件放在一个固定的位置上。下面是将一个组件定位到某个绝对定位的步骤:1)将布局管理器... 查看详情
周强201771010141《面向对象程序设计(java)》第七周学习总结(代码片段)
实验目的与要求(1)进一步理解4个成员访问权限修饰符的用途; (2)掌握Object类的常用API用法;(3)掌握ArrayList类用法与常用API;(4)掌握枚举类使用方法;(5)结合本章知识,理解继承与多态性两个面向对象程序设计... 查看详情
周强201771010141《面向对象程序设计(java)》第六周学习总结
枚举是一种特殊的数据类型,之所以特殊是因为它既是一种类(class)类型却又比类型多了些特殊的约束,但是这些约束的存在也造就了枚举类型的简洁,安全性以及便捷性。创建枚举类型要使用enum关键字,隐含了所创建的... 查看详情
周强201771010141《面向对象程序设计(java)》第九周实验总结(代码片段)
实验部分1、实验目的与要求(1)掌握java异常处理技术;(2)了解断言的用法;(3)了解日志的用途;(4)掌握程序基础调试技巧;2、实验内容和步骤实验1:用命令行与IDE两种环境下编辑调试运行源程序ExceptionDemo1、ExceptionDemo2,结... 查看详情
«面向对象程序设计(java)»第三周学习总结周强201771010141
实验目的与要求(1)进一步掌握Eclipse集成开发环境下java程序开发基本步骤;(2)熟悉PTA平台线上测试环境;(3)掌握Java语言构造基本程序语法知识(ch1-ch3);(4)利用已掌握Java语言基本程序设计知识,学习设计开发含有一... 查看详情
周强201771010141《面向对象与程序设计》(代码片段)
第一部分:理论知识学习部分 1.程序是一段静态的代码,它是应用程序执行的蓝本。进程是程序的一次动态执行,它对应了从代码加载、执行至执行完毕的一个完整过程。操作系统为每个进程分配一段独立的内存空间和系统... 查看详情
08-面向对象----j
一面向对象的程序设计的由来请参考:http://www.cnblogs.com/linhaifeng/articles/6428835.html二什么是面向对象的程序设计及为什么要有它面向过程的程序设计的核心是过程,过程即解决问题的步骤,面向过程的设计就好比精心设计好一条... 查看详情
2020面向对象设计与构造第三单元博客总结(代码片段)
面向对象设计与构造第三单元总结一、JML规格化设计JML,全称TheJavaModelingLanguage,是用于对Java程序进行规格化描述的注释性质语言。笔者在本文总结了常见的JML语法描述。1.注释结构在注释行或注释块中,以@开头的行被认作JML注... 查看详情
面向对象
老王和隔壁的美女猜数字,一共有四次机会,猜到了就有特殊奖励publicclasstest{publicstaticvoidmain(String[]args){inti=(int)(Math.random()*10);Scannerinput=newScanner(System.in);for(intj=0;j<4;j++){System.out.println("老王第"+(j+1)+"次 查看详情
201771010126王燕《面向对象程序设计(java)》第二周学习总结
201771010126王燕《面向对象程序设计(java)》第二周学习总结一.理论知识学习部分3.1j简单的java应用程序标识符由字母、下划线、美元符号和数字组成,且第一个符号不能为数字。标识符可用作:类名、变量名、方法名、数组名... 查看详情
201823072019-2020-1《数据结构与面向对象程序设计》实验1报告
课程:《程序设计与数据结构》班级:1823姓名:王美皓学号:20182322实验教师:王美皓实验日期:2019年9月9日必修/选修:必修1.实验内容基于命令行和IDE(IntelljIDEA简易教程](http://www.cnblogs.com/rocedu/p/4421202.html)进行简单的Java程... 查看详情
杨其菊201771010134《面向对象程序设计(java)》第三周学习总结(代码片段)
《面向对象程序设计(Java)》第三周学习总结第一部分:理论知识 这周课程没有新进度,由于感觉对基础语法的不熟悉,复习了一遍前三章的细碎知识,学到一些之前不知道的原理: 1.计算机高级语言按程序的... 查看详情
c++面向对象的主要体现是啥?
...得对我有用的话,我会再追加分。)C++面向对象是表现在程序设计的过程上,它是突破了C的结构化设计而出现的完全以实际问题为入手点的。C++的面向对象3个特性:1.封装。2.继承。3.多态。尤其重要的是,它采用类的设计,杜... 查看详情
徐思201771010132《面向对象程序设计(java)》第十二周学习总结(代码片段)
一、理论知识部分Java的抽象窗口工具箱(AbstractWindowToolkit,AWT)包含在java.awt包中,它提供了许多用来设计GUI的组件类和容器类。大部分AWT组件都有其Swing的等价组件,Swing组件的名字一般是在AWT组件名前面添加一个字母“J”。通... 查看详情
201771010110孔维滢《面向对象程序设计(java)》第十二周学习总结
理论知识部分1.Java的抽象窗口工具箱(AbstractWindowToolkit,AWT)包含在java.awt包中,它提供了许多用来设计GUI的组件类和容器类。2.Swing用户界面库是非基于对等体的GUI工具箱。Swing类库被放在javax.swing包里。3.大部分AWT组件都有其Swing... 查看详情
马凯军201771010116《面向对象与程序设计java》第十二周学习总结(代码片段)
一、理论与知识学习部分Java的抽象窗口工具箱(AbstractWindowToolkit,AWT)包含在java.awt包中,它提供了许多用来设计GUI的组件类和容器类。大部分AWT组件都有其Swing的等价组件,Swing组件的名字一般是在AWT组件名前面添加一个字母“J... 查看详情
201771010134杨其菊《面向对象程序设计java》第十二周学习总结(代码片段)
...bsp; 内容概要: AWT与Swing简介;框架的创建;图形程序设计; 显示图像;1.AWT组件:2.Swing组件层次关系3.AWT与Swing的关系:大部分AWT组件都有其Swing的等价组件; Swing组件的名字一般是在AWT组件名前面添加一个字母“J 查看详情
面向对象程序设计介绍以及面向对象的基本特征
面向对象的程序设计(ObjectOrientedProgramming,OOP)方法是目前比较流行的程序设计方法,和面向过程的程序设计比,它更符合人类的自然思维方式。在面向过程程序设计中,程序=数据+算法,数据和对数据的操作是分离的,如... 查看详情