본문 바로가기

자바

2주차 은행 계좌 예제 수정

선언 클래스에서 메서드를 더 적극 활용해보면서 구동 클래스에서는 호출로 좀 더 가독성을 높이려고 했다. 
package test1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import test1.*;
-----------------------------------------선언 클래스--------------------------------------
public class AccountInfo {
	private String name;
	private String account;
	private int balance;
	AccountInfo(String name, String account, int balance) {
		this.name = name;
		this.account = account;
		this.balance = balance;
	}
	public void create() throws InvalidValueException {
		System.out.print(" 계좌번호 : ");
		account = getUserInput();
		System.out.print("예금주 : ");
		name = getUserInput();
		System.out.print("최초입금 :");
		balance = Integer.parseInt(getUserInput());
		if (balance <= 0) {
			throw new InvalidValueException("[에러] 최초금액은 0원 이상입니다.");
		}
		new AccountInfo(account, name, balance);
		System.out.println("입력이 완료되었습니다.");
	}
	public void deposit() throws InvalidValueException {
		System.out.print("입금할 금액을 입력하세요.");
		int money = Integer.parseInt(getUserInput());
		if (money <= 0) {
			throw new InvalidValueException("최소 금액은 0원 이상입니다.");
		}
		this.balance += money;
		System.out.println(money + " 원 정상입금되었습니다.");
	}
	public void withdraw() throws InvalidValueException {
		// TODO 출금할 금액이 잘못 입력되었거나, 잔액이 부족한 경우 예외 발생
		System.out.print("출금할 금액을 입력하세요.");
		int money = Integer.parseInt(getUserInput());
		if (balance < money) {
			throw new InvalidValueException("[에러]!! 잔고 부족 :" + (money - balance) + " 원모자람");
		}
		if (money < 0) {
			throw new InvalidValueException("[에러]!! 출금할 금액은 0원 초과로 입력해");
		}
		this.balance -= money;
		System.out.println(money + "원 정상 출금되었습니다.");
	}
	public static String getUserInput() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String inputString = null;
		try {
			inputString = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return inputString;
	}
	public void showInfo() throws AccountNotFoundException {
		if (account == null && name == null && balance == 0) {
			throw new AccountNotFoundException("[에러] 계좌가 없습니다.");
		}
		System.out.println("[account]: " + account + ", [name]: " + name + ", [balance] :" + balance);
	}
}
	--------------------------------------구동 클래스------------------------------------
<같은 패키지 다른 클래스 파일로 저장>
package test1;
import java.util.*;
import java.util.Scanner;
import test1.*;
public class AccountTest {
	public static void main(String[] args) throws InvalidValueException, AccountNotFoundException {
		int num = 0;
		Scanner scan = new Scanner(System.in);
		AccountInfo ac;
		while (num != 9) {
			printMenu();
			try {
				num = scan.nextInt();
				scan.nextLine();
				ac = new AccountInfo(null, null, 0);
				switch (num) {
				case 1:
					ac.create();
					break;
				case 2:
					ac.showInfo();
					break;
				case 3:
					ac.deposit();
					break;
				case 4:
					ac.withdraw();
					break;
				case 9:
					System.out.println("종료합니다.");
					break;
				}
			} catch (InvalidValueException e) {
				System.out.println(e.getMessage()); // TODO catch 세분화 (각각의 예외 상황 별로
			} catch (AccountNotFoundException e) {
				System.out.println(e.getMessage());
			} catch (InputMismatchException e) {
				scan = new Scanner(System.in);
				System.out.println("잘못 입력했습니다. 정수만 입력가능 ");
//				e.printStackTrace();
//				System.out.println(e.getClass().getName()+"예외가"+e.getMessage()+"때문에 발생했습니다.");
			}
		}
	}
	private static void printMenu() {
		System.out.println("\n===== < 메뉴 > =====");
		System.out.println(" 1. 계좌 생성");
		System.out.println(" 2. 계좌 정보 출력");
		System.out.println(" 3. 입금");
		System.out.println(" 4. 출금");
		System.out.println(" 9. 종료");
		System.out.println("===================");
		System.out.print(">> 메뉴 : ");
	}
}
---------------------사용자 정의 예외 처리-------------------------------------------
package test1;
//부모 클래스인 Exception을 상속받아 사용자가 정의(customException)한 클래스를 사용할 수 있다.
public class AccountNotFoundException extends Exception {
	public AccountNotFoundException(String msg) {
        super(msg);
    }
}
package test1;
public class InvalidValueException extends Exception {
    public InvalidValueException(String msg) {
        super(msg);
    }
}

 

 올바른 코드를 아직 정확히 사용하고 있지는 못하지만 계속해서 버전을 업그레이드 해가면서 내 것으로 만들어야겠다.
수정과 추가 해보면 좋을 것들 :
1. 객체를 적극 사용하여 인터페이스와,상속과 같은 기능을 사용해보자
2. 배열을 활용하여 인덱스길이 10정도의 배열을 생성하고 더 다양한 메서드를 이용하여 기능 추가해볼것
ex) search, delete, 
3. 또 다른 클래스를 생성하여 서로 고객들간 간단한 송금,이체 서비스
4. 좀 더 구체적인 기능 추가 하되 단계별로 차근차근히 추가하기

 

'자바' 카테고리의 다른 글

Day11  (0) 2021.05.18
Day10-1  (0) 2021.05.17
Day09  (0) 2021.05.14
Day08  (0) 2021.05.13
Day07  (0) 2021.05.13