[Mini Project] Library Service : Rent 관련 메서드(Method for Rent)

2022. 2. 26. 02:00·◈ Human Project/Mini : Library Service📚
728x90


- Library Service : Rent 관련 메서드(method for Rent)

1. Rent 관련 주요 메서드

rentBook(int userID) : 대여하고자 하는 도서를 검색하고, 검색한 도서를 대여하는 메서드.

@param userID : 도서를 대여하려는 계정의 ID(User 클래스의 id)

 

public void rentBook(int userID) { // 대여 기능
    if (findUserByID(userID) != null) {
        System.out.println("대여할 도서를 검색해주세요.");
        List<Book> sBooks = searchBook();

        if (sBooks.size() > 0) {
            rentIndex();
            int cnt = 1;
            for (Book b : sBooks) {
                System.out.printf("│ %2d │ ", cnt++);
                System.out.print(convertLeft(bookTitleLength(b), 24) + " │ ");
                System.out.print(convertLeft(bookAuthorLength(b), 20) + " │ ");
                System.out.print(convertLeft(bookPublisherLength(b), 20) + " │  ");
                System.out.println(convert(b.getAmount() + "", 2) + "권  │");
                System.out.printf("────────────────────────────────────────────────────────────────────────────────────────%n");
            }
            int rentNum = nextInt("대여할 도서의 번호를 입력해주세요. > ") - 1;

            if (!(rentNum < 0 || rentNum > sBooks.size())) {

                Book rBook = sBooks.get(rentNum);
                bookIndex();
                System.out.print("│     " + convert(rBook.getId() + "", 3) + "    │ ");
                System.out.print(convertLeft(bookTitleLength(rBook), 24) + " │ ");
                System.out.print(convertLeft(bookAuthorLength(rBook), 20) + " │ ");
                System.out.print(convertLeft(bookPublisherLength(rBook), 20) + " │ ");
                System.out.print(convertLeft(rBook.getIsbn(), 10) + " │  ");
                System.out.println(convert(rBook.getAmount() + "", 2) + "권  │");
                System.out.println("────────────────────────────────────────────────────────────────────────────────────────────────────────────────");

                if (nextInt("대여하시겠습니까?[1.네 2.아니오] > ") == 1) {
                    // 대여할 도서가 있는 경우
                    if (rBook.getAmount() > 0) {
                        rent(rBook, userID);
                    // 모든 도서가 대여 중일 경우
                    } else {
                        System.out.println("현재 모든 책이 대여 중입니다.");
                    }
                }
            } else {
                System.out.println("잘못 입력하셨습니다.");
            }
        }
    } else {
        System.out.println("ID를 확인해주세요.");
    }
}

 

rentBook(int userID) / 도서대여


returnBook(int userID) : 대여한 도서목록을 확인하고 대여한 도서를 반납하는 메서드.

@param userID : 도서를 반납하려는 계정의 ID(User 클래스의 id)

 

public void returnBook(int userID) throws ParseException { // 반납 기능 >> userID 입력 필요
    System.out.println("도서반납입니다.");
    List<Rent> rBooks = new ArrayList<Rent>();
    int cnt = 1;
    rentListIndex();
    for (Rent r : rents) {
        if (r.getUserID() == userID /* logIn 한 userID */ && findLibBookByID(r.getLibBookID()).isRent() == true) {
            System.out.printf("│ %2d │   ", cnt++);
            System.out.print(convert(r.getRentNum() + "", 4) + "   │ ");
            System.out.print(convertLeft(bookTitleLength(findBookByLibBookID(r.getLibBookID())), 24) + " │ ");
            System.out.print(convertLeft(bookAuthorLength(findBookByLibBookID(r.getLibBookID())), 20) + " │ ");
            System.out.print(convertLeft(bookPublisherLength(findBookByLibBookID(r.getLibBookID())), 20) + " │ ");
            System.out.print(convertLeft(dateFormat(r.getDateRent()), 10) + " │    ");
            System.out.println(convertLeft(findOverdueByRent(r), 4) + "    │");
            System.out.printf("────────────────────────────────────────────────────────────────────────────────────────────────────────────────────%n");
            rBooks.add(r);
        }
    }
    if (rBooks.size() > 0) {
        int returnNum = nextInt("반납할 도서의 번호를 입력해주세요. > ") - 1;
        if (!(returnNum < 0 || returnNum > rBooks.size())) {
            changeReturnState(rBooks.get(returnNum));
            rBooks.get(returnNum).setDateReturn(System.currentTimeMillis());
            System.out.println("반납완료");
        } else {
            System.out.println("잘못 입력하셨습니다.");
        }
    } else {
        System.out.println();
        System.out.println("반납할 도서가 없습니다.");
    }
}

 

returnBook(int userID) / 도서반납
returnBook(int userID) / 도서반납(연체여부 확인)


rentList(int userID) : 도서대여이력을 출력하는 메서드. 대여여부 및 대여일, 반납일을 확인할 수 있다. 일반 계정은 자신의 도서대여이력만 볼 수 있고, 관리자 계정은 전체 도서대여이력을 볼 수 있다.

@param userID : 대여이력을 확인하고자 하는 계정의 ID(User 클래스의 id)

 

public void rentList(int userID) {
    System.out.println("도서대여이력입니다.");
    if (findUserByID(userID).isAdmin() == true) {
        listIndex();
        for (Rent r : rents) {
            System.out.print("│    " + convert(r.getRentNum() + "", 4) + "    │  ");
            System.out.print(convertLeft(userNameLength(findUserByID(r.getUserID())), 13) + "   │ ");
            System.out.print(convertLeft(bookTitleLength(findBookByLibBookID(r.getLibBookID())), 24) + " │ ");
            System.out.print(convertLeft(bookAuthorLength(findBookByLibBookID(r.getLibBookID())), 20) + " │ ");
            System.out.print(convertLeft(bookPublisherLength(findBookByLibBookID(r.getLibBookID())), 20) + " │ ");
            System.out.print(convertLeft(dateFormat(r.getDateRent()), 10) + " │ ");
            System.out.print(convertLeft(checkDateReturn(r), 10) + " │   ");
            System.out.println(convert(checkRentState(findLibBookByID(r.getLibBookID())), 4) + "   │");
            System.out.printf("───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────%n");
        }
    } else {
        listIndex();
        for (Rent r : rents) {
            if (r.getUserID() == userID /* logIn 한 userID */) {
                System.out.print("│    " + convert(r.getRentNum() + "", 4) + "    │  ");
                System.out.print(convertLeft(userNameLength(findUserByID(userID)), 13) + "   │ ");
                System.out.print(convertLeft(bookTitleLength(findBookByLibBookID(r.getLibBookID())), 24) + " │ ");
                System.out.print(convertLeft(bookAuthorLength(findBookByLibBookID(r.getLibBookID())), 20) + " │ ");
                System.out
                        .print(convertLeft(bookPublisherLength(findBookByLibBookID(r.getLibBookID())), 20) + " │ ");
                System.out.print(convertLeft(dateFormat(r.getDateRent()), 10) + " │ ");
                System.out.print(convertLeft(checkDateReturn(r), 10) + " │   ");
                System.out.println(convert(checkRentState(findLibBookByID(r.getLibBookID())), 4) + "   │");
                System.out.printf("───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────%n");
            }
        }
    }
}

 

rentList(int userID) / 도서대여이력


2. Rent 관련 보조 메서드

matchLibBook(Book rBook) : 대여 가능한 소장도서번호를 찾는 메서드. 대여 가능한 도서가 없을 경우, null을 반환한다.

@param rBook : 대여하려는 도서의 도서정보(Book 타입)
@return 대여 가능한 소장도서번호(LibBook 클래스의 id) 반환

 

private int matchLibBook(Book rBook) {
    LibBook libBook = null;
    for (LibBook l : lBooks) {
        if (l.getBookID() == rBook.getId() && l.isRent() == false) {
            libBook = l;
            libBook.setRent(true);
            break;
        }
    }
    return libBook.getId();
}

rent(Book rBook, int userID) : 해당 도서를 대여상태로 바꿔주는 메서드. matchLibBook()에서 대여가능 도서를 조회하여 대여 가능한 도서가 있으면 해당 소장도서의 대여여부(LibBook 클래스의 rent)를 true로 변경한다. 해당 도서의 재고(Book 클래스의 amount)도 1 감소시킨다.

@param rBook : 대여하려는 도서의 도서정보(Book 타입)
@param userID : 도서를 대여하는 계정의 ID(User 클래스의 id)

 

private void rent(Book rBook, int userID) {
    rents.add(new Rent(rents.get(rents.size() - 1).getRentNum(), userID, matchLibBook(rBook)));
    rBook.setAmount(rBook.getAmount() - 1);
    System.out.println("대여완료");
}

checkRentState(LibBook libBook) : 소장도서의 대여여부를 문자열로 반환하는 메서드. 대여여부가 true면 "대여", false면 "보유"를 반환한다.

@param libBook : 대여여부를 문자열로 반환하려는 소장도서정보(LibBook 타입)
@return libBook.isRent()가 true면 "대여", false면 "보유"를 문자열로 반환

 

private String checkRentState(LibBook libBook) {
    if (libBook.isRent() == true) {
        return "대여";
    } else {
        return "보유";
    }
}

changeReturnState(Rent returnBook) : 대여 중인 도서를 반납하면 대여상태를 '보유'로 바꿔주는 메서드. 반납이 완료되면 해당 도서의 재고(Book 클래스의 amount)도 1 증가시킨다.

@param returnBook : 반납할 도서의 대여정보(Rent 타입)

 

private void changeReturnState(Rent returnBook) {
    for (LibBook l : lBooks) {
        if (l.getId() == returnBook.getLibBookID()) {
            l.setRent(false);
            findBookByLibBookID(l.getId()).setAmount(findBookByLibBookID(l.getId()).getAmount() + 1);
        }
    }
}

dateFormat(long time) : 1/1000초(ms) 단위를 날짜형태로 변환해주는 메서드. 'yyyy-MM-dd'로 출력한다.

@param time : 날짜형태로 변환할 시간(ms : 1/1000초 단위)
@return 'yyyy-MM-dd' 양식의 문자열로 반환

 

private String dateFormat(long time) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    return dateFormat.format(time);
}

checkDateReturn(Rent rent) : 반납일을 문자열로 반환하는 메서드. 반납되지 않은 도서는 공백으로 반환한다.

@param rent : 반납일을 문자열로 반환할 대여정보(Rent 타입)
@return 반납일이 기록된 도서는 반납일을, 반납되지 않은 도서는 공백으로 반환

 

private String checkDateReturn(Rent rent) {
    if (rent.getDateReturn() == 0) {
        return "";
    } else {
        return dateFormat(rent.getDateReturn());
    }
}

findOverdueByRent(Rent rent) : 연체일을 계산하는 메서드. 대여일로부터 7일이 지나면 문자열 "연체"를 반환한다.

@param rent : 연체일을 계산할 대여정보(Rent 타입)
@return 대여일로부터 7일이 지나면 문자열 "연체" 반환
@throws ParseException 문자열을 ms 단위로 변환할 때 발생하는 예외상황

 

private String findOverdueByRent(Rent rent) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    long returnTime = dateFormat.parse(dateFormat.format(rent.getDateRent())).getTime() + 1000 * 60 * 60 * 24 * 7;

    if (System.currentTimeMillis() > returnTime) {
        return "연체";
    } else {
        return "";
    }
}
728x90
'◈ Human Project/Mini : Library Service📚' 카테고리의 다른 글
  • [Mini Project] Library Service : 기능 보조 메서드(데이터 출력 관련)
  • [Mini Project] Library Service : 기능 보조 메서드(findBy)
  • [Mini Project] Library Service : User 관련 메서드(method for User)
  • [Mini Project] Library Service : Book 관련 메서드(method for Book)
예르미(yermi)
예르미(yermi)
끊임없이 제 자신을 계발하는 개발자입니다👨🏻‍💻
  • 예르미(yermi)
    예르미의 코딩노트
    예르미(yermi)
  • 전체
    오늘
    어제
    • 분류 전체보기 (937)
      • ◎ Java (133)
        • Java☕ (93)
        • JSP📋 (26)
        • Applet🧳 (6)
        • Interview👨🏻‍🏫 (8)
      • ◎ JavaScript (48)
        • JavaScript🦎 (25)
        • jQuery🌊 (8)
        • React🌐 (2)
        • Vue.js🔰 (6)
        • Node.js🫒 (3)
        • Google App Script🐑 (4)
      • ◎ HTML5+CSS3 (17)
        • HTML5📝 (8)
        • CSS3🎨 (9)
      • ──────────── (0)
      • ▣ Framework (67)
        • Spring🍃 (36)
        • Spring Boot🍀 (12)
        • Bootstrap💜 (3)
        • Selenium🌕 (6)
        • MyBatis🐣 (10)
      • ▣ Tools (47)
        • API🎯 (18)
        • Library🎲 (15)
        • JitPack🚀 (3)
        • Jenkins👨🏻 (7)
        • Thymeleaf🌿 (4)
      • ▣ Server (32)
        • Apache Tomcat🐱 (14)
        • Apache HTTP Server🛡️ (1)
        • Nginx🧶 (7)
        • OracleXE💿 (4)
        • VisualSVN📡 (4)
      • ▣ OS : 운영체제 (18)
        • cmd : 명령프롬프트💻 (10)
        • Linux🐧 (8)
      • ▣ SQL : Database (56)
        • Oracle SQL🏮 (26)
        • PL SQL💾 (9)
        • MySQL🐬 (6)
        • MariaDB🦦 (6)
        • H2 Database🔠 (3)
        • SQL 실전문제🐌 (6)
      • ────────── (0)
      • ◈ Human Project (86)
        • Mini : Library Service📚 (15)
        • 화면 설계 [HTML]🐯 (10)
        • 서버 프로그램 구현🦁 (15)
        • Team : 여수어때🛫 (19)
        • Custom : Student🏫 (9)
        • Custom : Board📖 (18)
      • ◈ Yermi Project (40)
        • 조사모아(Josa-moa)📬 (5)
        • Riddle-Game🧩 (6)
        • 맛있을 지도🍚 (2)
        • 어디 가! 박대리!🙋🏻‍♂️ (5)
        • 조크베어🐻‍❄️ (4)
        • Looks Like Thirty🦉 (2)
        • Toy Project💎 (12)
        • 오픈소스 파헤치기🪐 (4)
      • ◈ Refactoring (15)
        • Mini : Library Service📚 (8)
        • 서버 프로그램 구현🦁 (1)
        • Team : 여수어때🛫 (0)
        • 쿼리 튜닝일지🔧 (6)
      • ◈ Coding Test (89)
        • 백준(BOJ)👨🏻‍💻 (70)
        • 프로그래머스😎 (2)
        • 코드트리🌳 (7)
        • 알고리즘(Algorithm)🎡 (10)
      • ◈ Study (102)
        • 기초튼튼 개발지식🥔 (25)
        • HTTP 웹 지식💡 (4)
        • 클린코드(Clean Code)🩺 (1)
        • 디자인패턴(GoF)🥞 (12)
        • 다이어그램(Diagram)📈 (4)
        • 파이썬(Python)🐍 (16)
        • 에러노트(Error Note)🧱 (34)
        • 웹 보안(Web Security)🔐 (6)
      • ◈ 공부모임 (39)
        • 혼공학습단⏰ (18)
        • 코드트리 챌린지👊🏻 (2)
        • 개발도서 100독👟 (8)
        • 나는 리뷰어다🌾 (11)
      • ◈ 자격증 공부 (37)
        • 정보처리기사🔱 (16)
        • 정보처리산업기사🔅 (9)
        • 컴퓨터활용능력 1급📼 (12)
      • ─────────── (0)
      • ◐ 기타 (113)
        • 알아두면 좋은 팁(tip)✨ (46)
        • 개발자의 일상🎈 (44)
        • 개발도서 서평🔍 (10)
        • 개발관련 세미나🎤 (2)
        • 블로그 꾸미기🎀 (9)
        • 사도신경 프로젝트🎚️ (2)
  • 인기 글

  • 최근 댓글

  • 태그

    백준 티어
    Java
    코딩
    일상
    jsp
    javascript
    Oracle
    Error Note
    꿀팁
    CSS
    BOJ
    자바스크립트
    spring
    Database
    백준
    Project
    프로그래밍
    SQL
    코딩 테스트
    html
  • 250x250
  • hELLO· Designed By정상우.v4.10.3
예르미(yermi)
[Mini Project] Library Service : Rent 관련 메서드(Method for Rent)
상단으로

티스토리툴바