1. 程式人生 > >Java面向物件與多執行緒綜合實驗(二)之 異常處理

Java面向物件與多執行緒綜合實驗(二)之 異常處理

理解異常的基本概念;瞭解Java異常的層次結構;熟悉並掌握Java異常的捕獲處理方法。
(1)閱讀Java™ Platform, Standard Edition 8 API Specification文件,瞭解後續程式設計中將要處理的IOException及其子類FileNotFoundException、EOFException,SocketException,SQLException以及執行時異常RuntimeException與其子類IllegalStateException。

(2)根據新提供的DataProcessing類(因還未講SQL,此類模擬異常出現情況,以一定概率隨機產生異常),在所編寫的Administrator、Operator和Browser類,增加異常處理功能。

  • User.java

import java.sql.SQLException;
import java.io.IOException;
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 abstract  void showMenu();
     public void showFileList() throws SQLException{
    	 double ranValue=Math.random();
    	 if(ranValue>0.5) throw new SQLException("Error in accessing file DB");
    	 System.out.println("列表……");
     }
     public boolean downloadFile() throws IOException{
    	 double ranValue=Math.random();
    	 if(ranValue>0.5) throw new IOException("Error in accessing file");
    	 System.out.println("下載檔案……");
    	 return true;
     }
     public boolean changeSelfInfo(String password) throws SQLException{
    	if(DataProcessing.update(name,password,role)) {
    		this.password=password;
    		System.out.println("修改成功!");
    		return true;
    	}
    	else {
    		System.out.println("修改失敗!");
    		return false;
    	}
     }
     public void exitSystem() {
    	 System.out.println("系統退出,謝謝使用!");
    	 System.exit(0);
     }
     public void setName(String name) {
    	 this.name=name;
     }
     public String getName() {
    	 return name;
     }
     public void setPassword(String password) {
    	 this.password=password;
     }
     public String getPassword() {
    	 return password;
     }
     public void setRole(String role) {
    	 this.role=role;
     }
     public String getRole() {
    	 return role;
     }
}

  • DataProcessing.java

import java.util.Enumeration;
import java.util.Hashtable;
import java.sql.*;

public class DataProcessing {
	private static boolean connectToDB=false;
    static Hashtable<String,User> users;
    static {
    	users=new Hashtable<String,User>();
    	users.put("hjy", new Operator("hjy","111","operator"));
    	users.put("cr", new Browser("cr","000","browser"));
    	users.put("myk", new Administrator("myk","250","administrator"));
    	Init();
    }
    public static void Init() {
    	//connect to database
   
    	//update database connection status
    	if(Math.random()>0.2) connectToDB=true;
    	else connectToDB=false;
    }
    public static User searchUser(String name) throws SQLException{
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	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("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	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("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	Enumeration<User> e=users.elements();
    	return e;
    }
    public static boolean update(String name,String password,String role) throws SQLException{
    	User user;
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	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
    			user=new Browser(name,password,role);
    		users.put(name, user);
    		return true;
    	}
    	else return false;
    }
    public static boolean insert(String name,String password,String role) throws SQLException{
    	User user;
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	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
    			user=new Browser(name,password,role);
    		users.put(name, user);
    		return true;
    	}
    }
    public static boolean delete(String name) throws SQLException{
    	if(!connectToDB) throw new SQLException("Not Connected to Database");
    	double ranValue=Math.random();
    	if(ranValue>0.5) throw new SQLException("Error in excecuting Query");
    	if(users.containsKey(name)) {
    		users.remove(name);
    		return true;
    	}
    	else return false;
    }
    public void disconnectFromDB() {
    	if(connectToDB) {
    		//close Statement and Connection
    		try {
    			if(Math.random()>0.5) throw new SQLException("Error in disconnecting DB");
    		}
    		catch(SQLException sqlException) {
    			sqlException.printStackTrace();
    		}finally {
    			connectToDB=false;
    		}
    	}
    }
}

  • Administrator.java

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Scanner;
public class Administrator extends User{
	private Scanner sc;
    Administrator(String name, String password, String role) {
		super(name, password, role);
	}
	public void changeUserInfo() {
		System.out.println("請輸入要修改的使用者姓名:");
    	String cn=sc.next();
    	System.out.println("請輸入新的使用者密碼:");
    	String cm=sc.next();
    	System.out.println("請輸入新的使用者角色:");
    	String cr=sc.next();
    	try {
			if(DataProcessing.update(cn, cm, cr)) {
				System.out.println("修改使用者資訊成功!");
			}
			else System.out.println("修改失敗!");
		} 
    	catch (SQLException e) {
    		System.out.println("檔案訪問錯誤"+e.getMessage());
		}
     }
    public void delUser() {
    	System.out.println("請輸入要刪除的使用者姓名:");
    	String dn=sc.next();
    	try {
			if(DataProcessing.delete(dn)) {
				System.out.println("刪除成功!");
			}
			else System.out.println("刪除失敗!該使用者不存在");
		} 
    	catch (SQLException e) {
    		System.out.println("檔案訪問錯誤"+e.getMessage());
		}
    }
    public void addUser() {
    	System.out.println("請輸入要增加的使用者姓名:");
    	String an=sc.next();
    	System.out.println("請輸入要增加的使用者密碼:");
    	String am=sc.next();
    	System.out.println("請輸入要增加的使用者角色:");
    	String ar=sc.next();
    	try {
			if(DataProcessing.insert(an, am, ar)) {
				System.out.println("增加使用者"+an+"成功!");
			}
			else System.out.println("增加使用者"+an+"失敗!");
		} 
    	catch (SQLException e) {
    		System.out.println("檔案訪問錯誤"+e.getMessage());
		}
    	
    }
    public void listUser() {
    	 Enumeration<User> e = null;
		try {
			e = DataProcessing.getAllUser();
		} 
		catch (SQLException e1) {
			System.out.println("檔案訪問錯誤"+e1.getMessage());
		}
    	 User user;
    	 while(e.hasMoreElements()) {
    		 user=e.nextElement();
    		 System.out.println("姓名:"+user.getName()+"密碼:"+user.getPassword()+"角色:"+user.getRole());
    	 }
    }
	public void showMenu() {
		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.退出");
    	sc=new Scanner(System.in);
    	int i=sc.nextInt();
    	switch(i) {
    	    case 1:{
    	    	changeUserInfo();
	    	    break;
    	    }
    	    case 2:{
	            delUser();
	            break;
    	    }
    	    case 3:{
    	        addUser();
    	    	break;
        	}
    	    case 4:{
    	        listUser();
    	        break;
        	}
    	    case 5:{
    	    	try {
					downloadFile();
				} 
    	    	catch (IOException e) {
					// TODO Auto-generated catch block
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 6:{
    	    	try {
					showFileList();
				} 
    	    	catch (SQLException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 7:{
    	    	System.out.println("請輸入新密碼:");
    	    	String psd=sc.next();
    	    	try {
					changeSelfInfo(psd);
				} 
    	    	catch (SQLException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 8:{
    	    	exitSystem();
    	    }
    	    default:{
    	    	System.out.println("輸入非法!請重新輸入!");
    	    	break;
    	    }
    	}
    	showMenu();
	}
}

  • Operator.java

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);
	}
    public void showMenu() {
    	System.out.println("歡迎進入檔案操作員選單!");
    	System.out.println("1.上傳檔案");
    	System.out.println("2.下載檔案");
    	System.out.println("3.檔案列表");
    	System.out.println("4.修改密碼");
    	System.out.println("5.退出");
    	@SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
    	int i=sc.nextInt();
    	switch(i) {
    	    case 1:{
    	        uploadFile();
    	        break;
        	}
    	    case 2:{
    	    	try {
					downloadFile();
				} 
    	    	catch (IOException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 3:{
    	    	try {
					showFileList();
				} 
    	    	catch (SQLException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 4:{
    	    	System.out.println("請輸入新密碼:");
    	    	String psd=sc.next();
    	    	try {
					changeSelfInfo(psd);
				} 
    	    	catch (SQLException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 5:{
    	    	exitSystem();
    	    }
    	    default:{
    	    	System.out.println("輸入非法!請重新輸入!");
    	    	break;
    	    }
    	}
    	showMenu();
    }
    public void uploadFile() {
    	//上傳檔案
    	System.out.println("上傳成功!");
    }
}

  • Browser.java

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);
	}
	public void showMenu() {
    	System.out.println("歡迎進入檔案瀏覽員選單!");
    	System.out.println("1.下載檔案");
    	System.out.println("2.檔案列表");
    	System.out.println("3.修改密碼");
    	System.out.println("4.退出");
    	System.out.print("請選擇:");
    	@SuppressWarnings("resource")
		Scanner sc = new Scanner(System.in);
    	int i=sc.nextInt();
    	switch(i) {
    	    case 1:{
    	    	try {
					downloadFile();
				} 
    	    	catch (IOException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 2:{
    	    	try {
					showFileList();
				} 
    	    	catch (SQLException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 3:{
    	    	System.out.println("請輸入新密碼:");
    	    	String psd=sc.nextLine();
    	    	try {
					changeSelfInfo(psd);
				} 
    	    	catch (SQLException e) {
    	    		System.out.println("檔案訪問錯誤"+e.getMessage());
				}
    	    	break;
    	    }
    	    case 4:{
    	    	exitSystem();
    	    }
    	    default:{
    	    	System.out.println("輸入非法!請重新輸入!");
    	    	break;
    	    }
    	}
    	showMenu();
    }
}

  • Main.java

import java.sql.SQLException;
import java.util.Scanner;
public class Main {
    public static void main(String args[]){
    	while(true) {
        	System.out.println("歡迎進入檔案管理系統!");
        	System.out.println("1.登入");
        	System.out.println("2.退出");
			@SuppressWarnings("resource")
			Scanner sc=new Scanner(System.in);
        	int i=sc.nextInt();
        	if(i==1) {
        		System.out.println("請輸入使用者名稱:");
        		String name=sc.next();
        		try {
					if(DataProcessing.searchUser(name)!=null) {
						System.out.println("請輸入密碼:");
						String password=sc.next();
						try {
						    if(DataProcessing.search( name ,password)!=null)
						        DataProcessing.search(name, password).showMenu();
						    else System.out.println("密碼錯誤!");  
						}
						catch(SQLException e) {
							System.out.println("資料庫錯誤"+e.getMessage());
						}
					}
					else {
					   System.out.println("使用者不存在!");   
					}
				} 
        		catch (SQLException e) {
        			System.out.println("資料庫錯誤"+e.getMessage());
				}
            }
        	else if(i==2) {
        		System.exit(0);
        	}
        	else {
        		System.out.println("輸入非法!請重新輸入。");
        	}
    	}
    }
}

以下是需要完成的結果展示:Java面向物件與多執行緒綜合實驗(二)之 異常處理