Hayden's Archive

[자바/Java] ArrayList를 이용하여 도서관 사서 프로그램 작성하기 본문

Study/Java & Kotlin

[자바/Java] ArrayList를 이용하여 도서관 사서 프로그램 작성하기

_hayden 2020. 4. 17. 23:05

관련 포스팅 : https://hayden-archive.tistory.com/62

 

[자바/Java] 도서관 사서 프로그램 작성하기

- VO Class : Book, Magazine // Magazine은 Book으로부터 상속받는다 - Service Class : BookManager // BookManager는 Book과 Magazine을 관리한다. 그리고 여기에 Javadoc를 작성한다. - Test Class : BookTest..

hayden-archive.tistory.com

- 이전에 썼던 소스 코드를 바탕으로 수정하였고 몇몇 기능을 추가하여 다시 작성하였다. 상속, 인터페이스, 싱글톤 패턴 같은 것들이 포함되었다.

 

- 유형이 비슷한 관련된 코드는 아래와 같이 포스팅했었다.

https://hayden-archive.tistory.com/69

 

[자바/Java] 상영 영화 관리 프로그램

- 도서관 사서 프로그램 ( 관련 포스팅 : https://hayden-archive.tistory.com/62?category=775873 )과 유사하지만 인터페이스를 추가하여 클래스가 인터페이스를 구현하도록 하고 CRUD에서 D 기능을 추가하였으며..

hayden-archive.tistory.com

https://hayden-archive.tistory.com/70

 

[자바/Java] 렌트 업체의 차량 정보 관리 프로그램

관련 포스팅 1. 도서관 사서 프로그램 https://hayden-archive.tistory.com/62?category=775873 2. 상영 영화 관리 프로그램 https://hayden-archive.tistory.com/69?category=775873 - Vehicle Super 클래스와 각..

hayden-archive.tistory.com

 

- 오늘 배운 ArrayList를 활용해서 다시 작성했는데 이전에 배열로 코드를 작성할 때보다 시간이 대폭 줄어들었다. 배열로 데이터를 뽑아낼 때는 여러 가지 요소를 고려하느라 고생했었는데 ArrayList를 알고 나니 다소 허망한 기분도 든다. 이렇게나 간편한 기능이 있었다니...ㅋㅋㅋㅋ

 

package com.encore.book;

public class Book {
	private String isbn;
	private String title;
	private String author;
	private String publisher;
	private double price;
	private String desc; // description. 간단한 설명
	
	public Book() {};
	
	public Book(String isbn, String title, String author, String publisher, double price, String desc) {
		super();
		this.isbn = isbn;
		this.title = title;
		this.author = author;
		this.publisher = publisher;
		this.price = price;
		this.desc = desc;
	}
	
	public String getIsbn() {
		return isbn;
	}

	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getPublisher() {
		return publisher;
	}

	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public String toString() {
		return " [" + isbn +", "+title+", "+author+", "+publisher+", "+price+", "+desc + "] ";
	}
	
}
package com.encore.magazine;

import com.encore.book.Book;

public class Magazine extends Book {
	private int year;
	private int month;
	
	public Magazine(String isbn, String title, String author, String publisher, double price, String desc, int year, int month) {
		super(isbn, title, author, publisher, price, desc);
		this.year = year;
		this.month = month;
	}
	
	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public String toString() {
		return super.toString() + ", "+ year + ", "+ month + " ]"; 
	}
}
package com.encore.bookmanager;

import java.util.ArrayList;

import com.encore.book.Book;

/*
 * BookManager 인터페이스는 다양한 Book 객체들을 핸들링하는 템플릿 기능을 가지고 있다.
 */
public interface BookMgr {
	// 내가 마음대로 만들지 않고 배포된 템플릿을 가지고 커스터마이즈 한다.
	// 팀 작업할 때 회의해서 method identify를 결정. 같이 협업할 때
	// 인터페이스는 가장 강력한 표준화된 규약
	// 인터페이스 하나 주면 리턴 타입 뭘로 하고 이런 얘기 안해도 됨. 
	
	void addBook(Book nBook);
	ArrayList<Book> getAllBook();
	Book searchBookByIsbn(String isbn);
	ArrayList<Book> searchBookByTitle(String title);
	ArrayList<Book> onlySearchBook();
	ArrayList<Book> onlySearchMagazine();
	ArrayList<Book> magazineOfThisYearInfo(int year);
	ArrayList<Book> searchBookByPublisher(String publisher);
	ArrayList<Book> searchBookByPrice(int price);
	int getTotalPrice();
	int getAvgPrice();

}
package com.encore.bookmanager;

import java.util.ArrayList;

import com.encore.book.Book;
import com.encore.magazine.Magazine;
/**
 * 
 * @author KimYeonhee
 * @since JDK 1.8.5
 * @version Start Version level 1.
 * @version 2 :: Singletone 적용...
 * @version 3 :: BookManager 인터페이스 템플릿 제공
 * @version 4 :: 배열을 대체하여 ArrayList 기능 적용
 *
 */
public class BookMgrImpl implements BookMgr {
	private ArrayList<Book> bList;
	
	private static BookMgrImpl mgr = new BookMgrImpl();
	
	private BookMgrImpl() {
		bList = new ArrayList<>(); // 배열과 달리 사이즈 지정 안 해줘도 됨
	}
	
	public static BookMgrImpl getInstance() {
		return mgr;
	}

	// 1. 데이터 입력 기능
	public void addBook(Book nBook) {
		boolean find = true;
		for(Book b : bList) {
			if(b.getIsbn().equals(nBook.getIsbn())) {
				System.out.println("도서명 : "+nBook.getTitle()+", 이미 소장하고 있는 책입니다.");
				find = false;
				break;
			}
		}
		if(find == true) {
			bList.add(nBook);
			System.out.println("도서명 : " + nBook.getTitle()+", 성공적으로 추가되었습니다. ");
		}
	}
	
	// 2. 데이터 전체 검색 기능
	public ArrayList<Book> getAllBook(){
		return bList;
	}
	
	// 3. isbn으로 정보를 검색하는 기능
	public Book searchBookByIsbn(String isbn) {
		Book temp = new Book();
		for(Book b : bList) if(b.getIsbn().equals(isbn)) temp = b;
		return temp;
	}
	
	// 4. title로 정보를 검색하는 기능
	public ArrayList<Book> searchBookByTitle(String title){
		ArrayList<Book> temp = new ArrayList<>();
		for(Book b : bList) if(b.getTitle().contains(title)) temp.add(b);
		return temp;
	}
	
	// 5. Book만 검색하는 기능
	public ArrayList<Book> onlySearchBook(){
		ArrayList<Book> temp = new ArrayList<>();
		for(Book b : bList) {
			if(b instanceof Magazine) continue;
			else temp.add(b);
		}
		return temp;
	}
	
	// 6. Magazine만 검색하는 기능
	public ArrayList<Book> onlySearchMagazine(){
		ArrayList<Book> temp = new ArrayList<>();
		for(Book b : bList) if(b instanceof Magazine) temp.add(b);
		return temp;
	}
	
	// 7. Magazine 중 올해 잡지만 검색하는 기능
	public ArrayList<Book> magazineOfThisYearInfo(int year){
		ArrayList<Book> temp = new ArrayList();
		for(Book b : bList) {
			if(b instanceof Magazine) {
				if(((Magazine) b).getYear() == year){
					temp.add(b);
				}
			}
		}
		return temp;
	}
	
	// 8. 출판사로 검색하는 기능
	public ArrayList<Book> searchBookByPublisher(String publisher){
		ArrayList<Book> temp = new ArrayList<>();
		for(Book b : bList) {
			if(b.getPublisher().equals(publisher)) temp.add(b);
		}
		return temp;
	}
	
	// 9. 가격으로 검색(인자로 주어진 가격보다 낮은 가격의 도서 검색)
	public ArrayList<Book> searchBookByPrice(int price){
		ArrayList<Book> temp = new ArrayList<>();
		for(Book b : bList) {
			if(b.getPrice() < price) {
				temp.add(b);
			}
		}
		return temp;
	}
	
	// 10. 저장된 모든 도서의 금액의 합을 구하는 기능
	public int getTotalPrice() {
		int total = 0;
		for(Book b : bList) total += b.getPrice(); 
		return total;
	}
	
	// 11. 저장된 모든 도서의 금액 평균을 구하는 기능
	public int getAvgPrice() {
		return getTotalPrice() / bList.size();
	}
}
package test;

import java.util.ArrayList;
import java.util.Scanner;

import javax.swing.plaf.synth.SynthSeparatorUI;

import com.encore.book.Book;
import com.encore.bookmanager.BookMgrImpl;
import com.encore.magazine.Magazine;

public class BookTest {

	public static void main(String[] args) {// 소장책 DB
		
		ArrayList<Book> bs = new ArrayList<>();
		
		bs.add(new Book("9788937485619", "잃어버린 시간을 찾아서", "마르셀 프루스트", "민음사", 8500.0, "『타임스』, 『르 몽드』 선정 20세기 최고의 책"));
		bs.add(new Book("9788954620512", "데미안", "헤르만 헤세", "민음사", 8500.0, "불안한 젊음에 바치는 영혼의 자서전"));
		bs.add(new Magazine("9788954620260", "어린이 과학동아", "편집부", "동아사이언스", 8500.0, "초등학생을 위해 한달에 두 번 발행하는 과학만화 잡지", 2020, 3));
		bs.add(new Book("9771975252008", "시간 가게", "이나영", "문학동네", 9900.0, "제 13회 문학동네 어린이 문학상 수상작"));
		bs.add(new Magazine("9771228402006", "씨네21", "편집부", "씨네21", 3800.0, "대한민국의 영화 전문 잡지", 2020, 4));
		bs.add(new Magazine("9771227130009", "뉴턴", "편집부", "아이뉴턴", 12000.0, "한중일에서 동시에 발행되고 있는 세계적인 과학 전문지", 2019, 11));
		bs.add(new Book("9788937460586", "싯다르타", "헤르만 헤세", "민음사", 6300.0, "헤세가 소설로 형상화한 부처의 생애"));
		bs.add(new Book("9788937460586", "싯다르타", "헤르만 헤세", "민음사", 6300.0, "헤세가 소설로 형상화한 부처의 생애"));
		
		printBooks(bs);
	}
	
	
	public static void printBooks(ArrayList<Book> bs) {// 출력 메소드
		
		BookMgrImpl service = BookMgrImpl.getInstance(); 
		
		// 메인 메소드의 배열에서 받아온 소장책 객체들을 service에 있는 ArrayList에 추가함
		for(Book b : bs) {
			System.out.println(b);
			service.addBook(b);
		}
		
		boolean menu = true; // 메뉴 스위치
		while(menu == true) { // 메뉴 스위치가 켜져있는 동안 무한반복
			System.out.println("===============================");
			System.out.println("S 전자 오픈 도서관 관리 페이지입니다.");
			System.out.println("1. 조회하기");
			System.out.println("2. 추가하기");
			System.out.println("3. 책 찾기");
			System.out.println("4. 전체책 가격 합계 및 평균 조회");
			System.out.println("===============================");
			
			Scanner sc = new Scanner(System.in);
			int choice = sc.nextInt(); // 메뉴 번호 입력

			// 1. 조회하기
			if(choice == 1) {
				System.out.println("===============================");
				System.out.println("어떤 방법으로 책을 조회하겠습니까?");
				System.out.println("1. 도서관 전체 소장책 조회하기");
				System.out.println("2. 일반도서만 조회하기(잡지 제외)");
				System.out.println("3. 잡지만 조회하기(일반도서 제외)");
				System.out.println("===============================");
				sc.nextLine();
				int search = sc.nextInt(); 
				if(search == 1) System.out.println(service.getAllBook());
				else if(search == 2) System.out.println(service.onlySearchBook());
				else if(search == 3) System.out.println(service.onlySearchMagazine());
			}

			// 2. 추가하기
			if(choice == 2) {
				System.out.println("ISBN을 입력하세요."); 
				String isbn = sc.next(); 
				System.out.println("책 제목을 입력하세요."); sc.nextLine();
				String title = sc.nextLine();
				System.out.println("작가를 입력하세요.");
				String author = sc.nextLine();
				System.out.println("출판사를 입력하세요.");
				String publisher = sc.nextLine();
				System.out.println("가격을 입력하세요.");
				Double price = sc.nextDouble(); sc.nextLine();
				System.out.println("간단한 설명을 입력하세요.");
				String desc = sc.nextLine();
				System.out.println("일반도서이면 true, 잡지이면 false를 입력하세요."); 
				Boolean bkOrMaga = sc.nextBoolean();
				if(bkOrMaga.equals(true)) {
					service.addBook(new Book(isbn, title, author, publisher, price, desc));
				}
				else if(bkOrMaga.equals(false)) {
					System.out.println("출간연도를 입력하세요.");
					int year = sc.nextInt();
					System.out.println("출간월을 입력하세요.");
					int month = sc.nextInt();
					service.addBook(new Magazine(isbn, title, author, publisher, price, desc, year, month));
				}
			}

			// 3. 책 찾기
			if(choice == 3) {
				System.out.println("===============================");
				System.out.println("어떤 방법으로 책을 찾겠습니까?");
				System.out.println("1. ISBN으로 책 찾기");
				System.out.println("2. 책 제목으로 책 찾기");
				System.out.println("3. 출간연도로 잡지 찾기");
				System.out.println("4. 출판사로 책 찾기");
				System.out.println("5. 특정 가격 밑으로 책 찾기");
				System.out.println("6. 이전으로");
				System.out.println("===============================");
				sc.nextLine();
				int search = sc.nextInt(); 

				if(search == 1) { // ISBN으로 책 찾기
					System.out.println("ISBN을 입력하세요.");
					String isbn = sc.next(); sc.nextLine();
					System.out.println(service.searchBookByIsbn(isbn));
				}
				else if(search == 2) { // 책 제목으로 책 찾기
					System.out.println("책 제목을 입력하세요.");  sc.nextLine();
					String title = sc.nextLine(); 
					System.out.println(service.searchBookByTitle(title));
				}
				else if(search == 3) { // 출간연도로 잡지 찾기
					System.out.println("출간연도를 입력하세요.(올해 --> 2020)"); 
					int year = sc.nextInt(); 
					System.out.println(service.magazineOfThisYearInfo(year));
				}
				else if(search == 4) { // 4. 출판사로 책 찾기
					System.out.println("출판사를 입력하세요.");
					String publisher = sc.next();
					System.out.println(service.searchBookByPublisher(publisher));
				}
				else if(search == 5) { // 5. 특정 가격 밑으로 책 찾기
					System.out.println("가격을 입력하세요.");
					int price = sc.nextInt(); sc.nextLine();
					System.out.println(service.searchBookByPrice(price));
				}
				else if(search == 6) menu = true; // 6. 이전으로
				else System.out.println("잘못 입력하셨습니다.");
			}

			// 4. 전체책 가격 합계 및 평균 조회
			if(choice == 4) {
				System.out.println("전체책 가격 합계 : " + service.getTotalPrice());
				System.out.println("전체책 가격 평균 : " + service.getAvgPrice());
			}
			
		}

	}

}