武汉理工大学-Java面向对象与多线程综合实验-(2)异常

实验目标

本实验目标在实验 (1) 的基础上,模拟数据库操作时产生的异常情况。实现的主要方法:在 DataProcessing 类中设置 connectToDB 布尔型变量判断是否连接数据库;通过 Math.random() 函数产生随机数模拟产生异常的概率;在异常情况下使用 throws 语句将产生的异常抛出。在角色类中,则要求进行用户操作时使用 try-catch 语句捕捉来自 DataProcessing 类的异常。

模块解析

本次实验比较简单,只需在前一次实验代码的基础上增加 try-catch 语句即可;eclipse 编译环境也提供了 try-catch 语句自动补全的功能,操作起来十分方便。模块结构与前一次实验相同。
模块结构图
在这里插入图片描述

源代码

本次实验代码基于实验 (1) 修改。

·DataProcessing

import java.sql.SQLException;
import java.util.*;

public class DataProcessing {

	private static boolean connectToDB = false;

	static Hashtable<String, User> users;
	static {
		users = new Hashtable<String, User>();
		users.put("jack", new Operator("jack", "123", "operator"));
		users.put("rose", new Browser("rose", "123", "browser"));
		users.put("kate", new Administrator("kate", "123", "administrator"));
		Init();
	}

	// 模拟数据库初始化方法
	public static void Init() {
		if (Math.random() > 0.2)
			connectToDB = true;
		else
			connectToDB = false;
	}

	public static User searchUser(String name) throws SQLException {

		// 未连接数据库抛出异常
		if (!connectToDB)
			throw new SQLException("未连接到数据库!");

		// 通过随机数模拟异常抛出
		double ranValue = Math.random();
		if (ranValue > 0.8)
			throw new SQLException("执行查询时出错!");

		if (users.containsKey(name)) {
			return users.get(name);
		}
		return null;
	}

	public static User search(String name, String password) throws SQLException {

		if (!connectToDB)
			throw new SQLException("未连接到数据库!");

		double ranValue = Math.random();
		if (ranValue > 0.8)
			throw new SQLException("执行查询时出错!");

		if (users.containsKey(name)) {
			User temp = users.get(name);
			if ((temp.getPassword()).equals(password))
				return temp;
		}
		return null;
	}

	public static Enumeration<User> getAllUser() throws SQLException {

		if (!connectToDB)
			throw new SQLException("未连接到数据库!");

		double ranValue = Math.random();
		if (ranValue > 0.8)
			throw new SQLException("执行查询时出错!");

		Enumeration<User> e = users.elements();
		return e;
	}

	public static boolean update(String name, String password, String role) throws SQLException {

		if (!connectToDB)
			throw new SQLException("未连接到数据库!");

		double ranValue = Math.random();
		if (ranValue > 0.8)
			throw new SQLException("执行更新时出错!");

		User user;
		if (users.containsKey(name)) {
			if (role.equalsIgnoreCase("administrator"))
				user = new Administrator(name, password, role);
			else if (role.equalsIgnoreCase("operator"))
				user = new Operator(name, password, role);
			else if (role.equalsIgnoreCase("browser"))
				user = new Browser(name, password, role);
			else
				return false;

			users.put(name, user);
			return true;
		} else
			return false;
	}

	public static boolean insert(String name, String password, String role) throws SQLException {

		if (!connectToDB)
			throw new SQLException("未连接到数据库!");

		double ranValue = Math.random();
		if (ranValue > 0.8)
			throw new SQLException("执行插入时出错!");

		User user;
		if (users.containsKey(name))
			return false;
		else {
			if (role.equalsIgnoreCase("administrator"))
				user = new Administrator(name, password, role);
			else if (role.equalsIgnoreCase("operator"))
				user = new Operator(name, password, role);
			else if (role.equalsIgnoreCase("browser"))
				user = new Browser(name, password, role);
			else
				return false;

			users.put(name, user);
			return true;
		}
	}

	public static boolean delete(String name) throws SQLException {

		if (!connectToDB)
			throw new SQLException("未连接到数据库!");

		double ranValue = Math.random();
		if (ranValue > 0.8)
			throw new SQLException("执行删除时出错!");

		if (users.containsKey(name)) {
			users.remove(name);
			return true;
		} else
			return false;
	}

	// 断开数据库连接
	public static void disconnectFromDB() throws SQLException {
		if (connectToDB) {
			if (Math.random() > 0.8) {
				throw new SQLException("断开数据库连接时出错!");
			}
			connectToDB = false;
		}
	}

}

新的 DataProcessing 类在于增加了数据库初始化方法,以及一定概率抛出异常的语句。
关于异常的相关内容读者可以自行学习,属于Java基本知识。

·User

import java.io.IOException;
import java.sql.SQLException;

public abstract class User {

	private String name;
	private String password;
	private String role;

	User(String name, String password, String role) {
		this.name = name;
		this.password = password;
		this.role = role;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	// 重写toString方法
	public String toString() {
		return "Name: " + this.name + " Password: " + this.password + " Role: " + this.role;
	}

	public abstract void showMenu();

	// 模拟抛出异常
	public boolean downloadFile(String filename) throws IOException {

		double ranValue = Math.random();
		if (ranValue > 0.8)
			throw new IOException("访问文件时出错!");

		System.out.println("下载文件...");
		return true;
	}

	public void showFileList() throws SQLException {

		double ranValue = Math.random();
		if (ranValue > 0.8)
			throw new SQLException("访问文件数据库时出错!");

		System.out.println("列表...");
	}

	public boolean changeSelfInfo(String password) throws SQLException {
		if (DataProcessing.update(name, password, role)) {
			this.password = password;
			return true;
		} else
			return false;
	}

	public void exitSystem() {
		System.out.println("系统退出, 谢谢使用 ! ");
		System.exit(0);
	}

}

User 类在原先基础上也增加了异常抛出,同时重写了 toString() 方法(方便对所有用户信息的打印)。

·Administrator

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

public class Administrator extends User {

	Administrator(String name, String password, String role) {
		super(name, password, role);
	}

	// 均增加try语句捕获异常
	public void updateUser(String input_name, String input_password, String input_role) {
		try {
			if (DataProcessing.update(input_name, input_password, input_role)) {
				System.out.println("修改成功!");
			} else {
				System.out.println("修改失败!输入角色不正确!");
			}
		} catch (SQLException e) {
			System.out.println(e.getLocalizedMessage());
		}

	}

	public void delUser(String input_name) {
		try {
			if (DataProcessing.delete(input_name)) {
				System.out.println("删除成功!");
			} else {
				System.out.println("删除失败!查找不到用户名!");
			}
		} catch (SQLException e) {
			System.out.println(e.getLocalizedMessage());
		}
	}

	public void addUser(String input_name, String input_password, String input_role) {
		try {
			if (DataProcessing.insert(input_name, input_password, input_role)) {
				System.out.println("添加成功!");
			} else {
				System.out.println("添加失败!用户名已存在/角色名不正确!");
			}
		} catch (SQLException e) {
			System.out.println(e.getLocalizedMessage());
		}
	}

	public void listUser() {
		try {
			// 通过tostring重写利用枚举类遍历
			Enumeration<User> s = DataProcessing.getAllUser();
			while (s.hasMoreElements()) {
				System.out.println(s.nextElement());
			}
		} catch (SQLException e) {
			System.out.println(e.getLocalizedMessage());
		}
	}

	@SuppressWarnings({ "resource" })
	@Override
	public void showMenu() {

		Scanner scan1 = new Scanner(System.in);
		Scanner scan2 = new Scanner(System.in);
		Scanner scan3 = new Scanner(System.in);
		Scanner scan4 = new Scanner(System.in);

		// 控制界面的开闭
		boolean administrator_isopen = true;
		// 记录用户的选择
		String administrator_choice;

		while (administrator_isopen) {

			// 界面显示
			System.out.println("=======欢迎进入档案管理员菜单=======");
			System.out.println("            1.修改用户");
			System.out.println("            2.删除用户");
			System.out.println("            3.新增用户");
			System.out.println("            4.列出用户");
			System.out.println("            5.下载文件");
			System.out.println("            6.文件列表");
			System.out.println("            7.修改密码");
			System.out.println("            8.退    出");
			System.out.println("====================================");
			System.out.print("请输入选项:");
			administrator_choice = scan1.next();

			if (administrator_choice.equals("1")) {

				System.out.print("请输入用户名:");
				String input_name = scan2.next();
				System.out.print("请输入密码:");
				String input_password = scan3.next();

				// 增加try语句捕获异常
				try {
					if (DataProcessing.search(input_name, input_password) != null) {

						System.out.print("请输入身份:");
						String input_role = scan4.next();

						this.updateUser(input_name, input_password, input_role);

					} else {
						System.out.println("用户名与密码不符!");
					}

				} catch (SQLException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (administrator_choice.equals("2")) {

				System.out.print("请输入用户名:");
				String input_name = scan2.next();

				this.delUser(input_name);

			} else if (administrator_choice.equals("3")) {

				System.out.print("请输入用户名:");
				String input_name = scan2.next();
				System.out.print("请输入密码:");
				String input_password = scan3.next();
				System.out.print("请输入身份:");
				String input_role = scan4.next();

				this.addUser(input_name, input_password, input_role);

			} else if (administrator_choice.equals("4")) {
				this.listUser();
			} else if (administrator_choice.equals("5")) {

				System.out.print("请输入文件名:");
				String filename = scan2.next();

				try {
					super.downloadFile(filename);
				} catch (IOException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (administrator_choice.equals("6")) {

				System.out.println("文件列表");
				try {
					super.showFileList();
				} catch (SQLException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (administrator_choice.equals("7")) {

				System.out.print("请输入新密码:");
				String newpassword = scan2.next();

				try {
					if (this.changeSelfInfo(newpassword)) {
						System.out.println("修改成功!");
					} else {
						System.out.println("修改失败");
					}
				} catch (SQLException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (administrator_choice.equals("8")) {
				administrator_isopen = false;
			} else {
				System.out.println("输入格式有误!请重新输入!");
			}

		}

	}
}

·Browser

import java.io.IOException;
import java.sql.SQLException;
import java.util.Scanner;

public class Browser extends User {

	Browser(String name, String password, String role) {
		super(name, password, role);
	}

	@SuppressWarnings("resource")
	@Override
	public void showMenu() {

		Scanner scan1 = new Scanner(System.in);
		Scanner scan2 = new Scanner(System.in);

		// 控制界面开关
		boolean browser_isopen = true;
		// 记录用户选择
		String browser_choice;

		while (browser_isopen) {

			// 显示页面
			System.out.println("=======欢迎进入档案浏览员菜单=======");
			System.out.println("            1.下载文件");
			System.out.println("            2.文件列表");
			System.out.println("            3.修改密码");
			System.out.println("            4.退    出");
			System.out.println("====================================");
			System.out.print("请输入选项:");
			browser_choice = scan1.next();

			if (browser_choice.equals("1")) {

				System.out.print("请输入文件名:");
				String filename = scan2.next();

				try {
					super.downloadFile(filename);
				} catch (IOException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (browser_choice.equals("2")) {

				System.out.println("文件列表");
				try {
					super.showFileList();
				} catch (SQLException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (browser_choice.equals("3")) {

				System.out.print("请输入新密码:");
				String newpassword = scan2.next();

				try {
					if (this.changeSelfInfo(newpassword)) {
						System.out.println("修改成功!");
					} else {
						System.out.println("修改失败");
					}
				} catch (SQLException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (browser_choice.equals("4")) {
				browser_isopen = false;
			} else {
				System.out.println("输入格式有误!请重新输入!");
			}

		}
	}
}

·Operator

import java.io.IOException;
import java.sql.SQLException;
import java.util.Scanner;

public class Operator extends User {

	Operator(String name, String password, String role) {
		super(name, password, role);
	}

	@SuppressWarnings({ "resource", "unused" })
	public void uploadFile() {

		Scanner scan1 = new Scanner(System.in);
		Scanner scan2 = new Scanner(System.in);
		Scanner scan3 = new Scanner(System.in);

		System.out.println("上传文件");
		System.out.print("请输入文件名:");
		String filename = scan1.next();
		System.out.print("请输入档案号:");
		String filenumber = scan2.next();
		System.out.print("请输入档案描述:");
		String fileDescribe = scan3.next();
		System.out.println("上传成功!");

	}

	@SuppressWarnings({ "resource" })
	@Override
	public void showMenu() {

		Scanner scan1 = new Scanner(System.in);
		Scanner scan2 = new Scanner(System.in);

		// 控制界面开关
		boolean operator_isopen = true;
		// 记录用户选择
		String operator_choice;

		while (operator_isopen) {

			// 显示界面
			System.out.println("=======欢迎进入档案录入员菜单=======");
			System.out.println("            1.上传文件");
			System.out.println("            2.下载文件");
			System.out.println("            3.文件列表");
			System.out.println("            4.修改密码");
			System.out.println("            5.退    出");
			System.out.println("====================================");
			System.out.print("请输入选项:");
			operator_choice = scan1.next();

			if (operator_choice.equals("1")) {
				this.uploadFile();
			} else if (operator_choice.equals("2")) {

				System.out.print("请输入文件名:");
				String filename = scan2.next();

				try {
					super.downloadFile(filename);
				} catch (IOException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (operator_choice.equals("3")) {

				System.out.println("文件列表");
				try {
					super.showFileList();
				} catch (SQLException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (operator_choice.equals("4")) {

				System.out.print("请输入新密码:");
				String newpassword = scan2.next();

				try {
					if (this.changeSelfInfo(newpassword)) {
						System.out.println("修改成功!");
					} else {
						System.out.println("修改失败");
					}
				} catch (SQLException e) {
					System.out.println(e.getLocalizedMessage());
				}

			} else if (operator_choice.equals("5")) {
				operator_isopen = false;
			} else {
				System.out.println("输入格式有误!请重新输入!");
			}

		}
	}
}

·Main

import java.sql.SQLException;
import java.util.Scanner;

public class Main {

	@SuppressWarnings({ "resource" })
	public static void main(String[] args) throws SQLException {

		Scanner scan1 = new Scanner(System.in);
		Scanner scan2 = new Scanner(System.in);
		Scanner scan3 = new Scanner(System.in);

		// 控制界面的开闭
		boolean main_isopen = true;
		// 用于记录用户的选择
		String main_choice;

		while (main_isopen) {

			// 界面显示
			System.out.println("=======欢迎进入档案系统=======");
			System.out.println("          1.登   录 ");
			System.out.println("          2.退   出 ");
			System.out.println("==============================");
			System.out.print("请输入选项:");
			main_choice = scan1.next();

			if (main_choice.equals("1")) {

				System.out.print("请输入用户名:");
				String input_name = scan2.next();
				System.out.print("请输入密码:");
				String input_password = scan3.next();

				// 增加try语句捕获异常
				try {
					User user = DataProcessing.search(input_name, input_password);
					if (user == null) {
						System.out.println("用户名与密码不符!");
					} else {
						user.showMenu();
					}
				} catch (SQLException e) {
					// getlocalizedMessage打出异常信息
					System.out.println(e.getLocalizedMessage());
				}

			} else if (main_choice.equals("2")) {
				try {
					// 断开连接,关闭界面
					DataProcessing.disconnectFromDB();
					main_isopen = false;
				} catch (SQLException e) {
					System.out.println(e.getLocalizedMessage());
				}
			} else {
				System.out.println("输入格式有误!请重新输入!");
			}

		}
		System.out.println("系统退出,感谢使用!");
	}

}

因为笔者不喜欢抛异常显示的红色语句 ,所以异常处理的 catch 语句块里用的是 e.getLocalizedMessage() 方法,其实其他的一些显示异常方法 e.printStackTrace() 等等也是正确的,问题不大。本实验重点在于学习 try-catch 语句的使用。

写在最后

声明:本文内容来源于武汉理工大学2019-2020学年Java编程实验,仅供学习参考。如有不足错误地方,还请指出。
代码建议不要无脑抄 ,很多细节没有详细讲解,读者需自行理解。编程是实践练出来的,祝愿读者在编程之路上不断进步!

发布了3 篇原创文章 · 获赞 0 · 访问量 178

猜你喜欢

转载自blog.csdn.net/weixin_43381409/article/details/104044446