java

42일차 가장 어려웠던 날, 실습 문제(완료) mqtt, item, book, mqtt, ArrayList로 단편적 db, 연동

비루블 2022. 8. 23. 18:59

요약정리

mqtt

오늘 한 itemservice 시험
NetworkView도 시험

20220823 웹보드 참고
언어활용에 대한 평가 첫과목 시험

오후에는 네트워크로 데이터가 바꼇을때 실시간 출력되게 하는 것이 시험

 

오전일과

오늘까지는 자바에서
평가 물품등록
entity> item.java

package com.example.entity;

import java.util.Date;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Getter // 가져가기
@Setter // 설정하기
@ToString // 현재 내용 출력
@NoArgsConstructor // default 생성자
@AllArgsConstructor // 5개 params항목을 설정 생성자
public class Item {
    
    private Long   no      = 0L; // 물품번호
    private String name    = "";
    private Long   price   = 0L;
    private Long quantity  = 0L;
    private Date regeDate  = null;

}


itemservice1

package com.example.service;

import java.util.List;

import com.example.entity.Item;

// 변수x, 구현부x, 정의o
public interface ItemService1 {
    
    // 등록하기
    public int insert(Item item);
    // 수정하기
    public int update(Item item);
    // 삭제하기
    public int delete(Item item);
    // 전체조회(페이지 네이션)
    public List<Item> selectList(int page);
    // 하나 조회
    public Item selectOne(Item item);
}

itemservice1impl

package com.example.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.example.config.MongoConfig;
import com.example.entity.Item;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertOneResult;
import com.mongodb.client.result.UpdateResult;

public class ItemService1Impl implements ItemService1 {

    private MongoCollection<Document> collection = null;

    public ItemService1Impl() {
        collection = MongoConfig.create().getConnection("item100");
    }



    @Override
    public int insert(Item item) {
        try {
            Document doc = new Document();
            doc.append("_id", item.getNo());
            doc.append("name", item.getName());
            doc.append("price", item.getPrice());
            doc.append("quantity", item.getQuantity());
            doc.append("regdate", new Date());

            InsertOneResult result = collection.insertOne(doc);
            System.out.println(result);
            if (result.getInsertedId().asInt64().getValue() == item.getNo()) {
                return 1;
            }
            return 0;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int update(Item item) {
        try{
            // 수정할 조건 정보
            Bson arg0 = Filters.eq("_id", item.getNo());

            // 수정할 항목들
            Bson arg1 = Updates.set("name", item.getName());
            Bson arg2 = Updates.set("price", item.getPrice());
            Bson arg3 = Updates.set("quantity", item.getQuantity());

            Bson arg4 = Updates.combine(arg1, arg2, arg3);

            UpdateResult result = this.collection.updateOne(arg0, arg4);
            System.out.println(result);
            if(result.getModifiedCount() == 1L){
                return 1;
            }
            return 0;
        }
        catch(Exception e){
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int delete(Item item) {
        try{
            Bson query = Filters.eq("_id", item.getNo()); // 2
            DeleteResult result = this.collection.deleteOne(query); // 1
            System.out.println(result);
            if(result.getDeletedCount() == 1L){
                return 1;
            }
            return 0;
        }
        catch(Exception e){
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public List<Item> selectList(int page) {
        Bson sort = Filters.eq("_id", 1);
        FindIterable<Document> list = collection.find().sort(sort).skip((page - 1) * 10).limit(10);

        List<Item> retList = new ArrayList<>();
        for (Document doc : list) {
            Item item = new Item();
            item.setNo(doc.getLong("_id"));
            item.setName(doc.getString("name"));
            item.setPrice(doc.getLong("price"));
            item.setQuantity(doc.getLong("quantity"));
            item.setRegeDate(doc.getDate("regdate"));
            retList.add(item);
        }
        return retList;
    }

    @Override
    public Item selectOne(Item item) {
        try{
            Bson query = Filters.eq("_id", item.getNo()); //검색조건
            MongoCursor<Document> cursor = collection.find(query).limit(1).cursor(); //1개 가져오기
            
            if ( cursor.hasNext() ) { //가져올 항목이 있는지 확인
                Document doc = cursor.next(); //1개 가져오기
    
                //Document -> Professor객체로 변환해서 리턴
                Item i = new Item();
                i.setNo(doc.getLong("_id"));
                i.setName( doc.getString("name") );
                i.setPrice( doc.getLong("price") );
                i.setQuantity( doc.getLong("quantity") );
                i.setRegeDate( doc.getDate("regdate") );
    
                return i;
            }
            return null;
            
        }
        catch(Exception e){
            e.getStackTrace();
            return null;
        }
    }
    
}


itemservice2 + impl 추상화

package com.example.service;

import java.util.List;

import com.example.entity.Item;


// 변수O, 구현부메소드O, 정의부 메소드O
public abstract class ItemService2 {
    //변수 만들기도 가능
    private int num = 0;
    // 등록하기
    public abstract int insert(Item item);
    // 수정하기
    public abstract int update(Item item);
    // 삭제하기
    public abstract int delete(Item item);
    // 전체조회(페이지 네이션)
    public abstract List<Item> selectList(int page);
    // 하나 조회
    public abstract Item selectOne(Item item);

    public void print(){
        System.out.println("테스트용");
    }
}


ItemView.java

package com.view;

import java.util.List;
import java.util.Scanner;

import com.example.entity.Item;
import com.example.mqtt.MyMqttClient;
import com.example.service.ItemService1;
import com.example.service.ItemService1Impl;

public class ItemView {

    // 서비스 객체 생성
    private ItemService1 itemService = new ItemService1Impl();
    private Scanner scanner = new Scanner(System.in);
    private MyMqttClient client = new MyMqttClient();


    // 생성자            
    public ItemView() throws Exception  {
        while(true) {
            System.out.println("1.물품등록");
            System.out.println("2.물품수정");
            System.out.println("3.물품삭제");
            System.out.println("4.물품조회(1개)");
            System.out.println("5.물품전체조회");
            System.out.println("0.종료");
            System.out.print("메뉴 선택 => ");
            int menu = scanner.nextInt();
            if(menu == 0){
                break;
            }
            else if(menu == 5) {
                menu5();
            }
            else if(menu == 4) {
                menu4();
            }
            else if(menu == 3) {
                menu3();
            }
            else if(menu == 2) {
                menu2();
            }
            else if(menu == 1) {
                menu1();
            }
        }
    }
    private void menu1(){
        System.out.print("물품번호, 물품명, 가격, 수량 입력 => ");
        String[] arr = scanner.next().split(",");

        Item item = new Item();
        item.setNo( Long.valueOf(arr[0].trim()));
        item.setName( arr[1].trim());
        item.setPrice( Long.valueOf(arr[2].trim()));
        item.setQuantity( Long.valueOf(arr[3].trim()));
        int ret = itemService.insert(item);
        if(ret == 1){
            System.out.println("등록성공");
        }
        else{
            System.out.println("등록실패");
        }
    }
    private void menu2(){
        System.out.print("물품번호, 물품명, 가격, 수량 입력 => ");
        String data = scanner.next();
        String[] arr = data.split(",");

        Item item = new Item();
        item.setNo( Long.valueOf(arr[0].trim()) );
        item.setName( arr[1].trim() );
        item.setPrice( Long.valueOf(arr[2].trim()) );
        item.setQuantity( Long.valueOf(arr[3].trim()) );

        int ret = itemService.update(item);
        if(ret == 1) {
            System.out.println("수정성공");
        }
        else {
            System.out.println("수정실패");
        }
    }
    private void menu3(){
        System.out.print("정보 입력 ex)1 => ");
        String data = scanner.next();

        Item item = new Item();
        item.setNo( Long.valueOf( data ) );

        int ret = itemService.delete(item);
        if(ret == 1) {
            System.out.println("삭제 성공");
        }
        else {
            System.out.println("삭제 실패");
        }
    }
    private void menu4(){
        scanner.nextLine(); // buffer비우기
        System.out.print("물품번호 입력 ex)1 => ");
        Long data = scanner.nextLong();
        Item item = new Item();
        item.setNo( Long.valueOf( data ) );
        System.out.println(itemService.selectOne(item)); 
    }
    private void menu5(){
        scanner.nextLine(); // buffer비우기
                
        List<Item> list 
            = itemService.selectList(1);

        for(Item tmp : list){
            System.out.println(tmp.toString());
        }
    }
}

 

 

중요중요중요중요중요중요중요중요중요중요중요중요중요중요중요중요중요중요중요중요

모니터링 하는 프로그램 구동해놓고 app.java

new NetworkView();

 

apptest에 가서 수정이나 삭제를 하는 것
받는 쪽을 평가하는데 혼자하니까 보내는 것도 해야함(apptest)

AppTest.java

package com.example;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

import com.example.entity.Item;
import com.example.mqtt.MyMqttClient;
import com.example.service.ItemService1;
import com.example.service.ItemService1Impl;

public class AppTest {

    // 객체 생성
    ItemService1 service = new ItemService1Impl();
    MyMqttClient client = new MyMqttClient();

    @Before
    public void before(){
        // 미리 실행할 메소드 객체 생성
    }


    // 물품등록
    // 1. service를 이용해서 DB에 추가
    // 2. mqtt로 메시지를 전송
    @Test
    public void iteminsert(){
        // 추가할 데이터 생성
        Item item = new Item(9L,"bbb", 200L,300L,null);
        // 서비스 호출
        int ret = service.insert(item);
        if(ret == 1){
            // {type:1, no:100}
            // object = > string
            JSONObject jobj = new JSONObject();
            jobj.put("type", 1);
            jobj.put("no", item.getNo());
            client.sendMessage(jobj.toString());
        }
        // assertEquals(1, ret);
    }

    @Test
    public void itemupdate(){
        // 추가할 데이터 생성
        Item item = new Item(9L,"수정된겁니다?", 200L,300L,null);
        // 서비스 호출
        int ret = service.update(item);
        if(ret == 1){
            // {type:1, no:100}
            // object = > string
            JSONObject jobj = new JSONObject();
            jobj.put("type", 2);
            jobj.put("no", item.getNo());
            client.sendMessage(jobj.toString());
        }
        // assertEquals(1, ret);
    }

    @Test
    public void itemdelete(){
        // 추가할 데이터 생성
        Item item = new Item(9L,"삭제", 200L,300L,null);
        // 서비스 호출
        int ret = service.delete(item);
        if(ret == 1){
            // {type:1, no:100}
            // object = > string
            JSONObject jobj = new JSONObject();
            jobj.put("type", 3);
            jobj.put("no", item.getNo());
            client.sendMessage(jobj.toString());
        }
        // assertEquals(1, ret);
    }

    @Test
    public void itemSelectList(){
        // List<Item> list = service.selectList(1);
        // for(Item item : list){
        //     System.out.println(item.toString());
        // }
        // // 반환값이 null아닌지 확인
        // assertNotNull(list);
    }
}



mymqtt recieve
//메시지가 올것임 여기로 다른쪽에 찍어볼 것. view> NetworkView.java
// 여기에 못와서 네트워크로 넣을 것임
// 1번이라는 것을 네트워크뷰로 보냄

MyMqttClient.java

package com.example.mqtt;

import org.bson.json.JsonObject;

// import javax.swing.JTextArea;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONObject;

import com.view.NetworkView;

// import com.view.NetworkView;

public class MyMqttClient implements MqttCallback {

    //   ws://127.0.0.1:1884,  tcp://127.0.0.1:1883
    private String broker = "tcp://1.234.5.158:11883";
    private String clientId = "db203_" + System.currentTimeMillis();
    private String userid = "ds606";
    private String password = "ds606";

    // 전송되는 메시지를 보관하는 방법
    private MemoryPersistence persistence = new MemoryPersistence(); 
    private MqttAsyncClient client = null;

    private NetworkView view = null;

    // private NetworkView view = new NetworkView();    
    
    // // Panel4의 output위치의 객체
    // private JTextArea output = null;
    
    public MyMqttClient() {
        try {
            client = new MqttAsyncClient(broker, clientId, persistence);

            MqttConnectOptions options = new MqttConnectOptions();
            options.setUserName(userid);
            options.setPassword(password.toCharArray());
            options.setCleanSession(true);

            client.connect(options);
            client.setCallback(this); //1. 객체를 전달함.

            System.out.println(this.client);// 접속객체
            Thread.sleep(1000);
        }
        catch(Exception e) {
            System.out.println("접속실패");
            e.printStackTrace();
        }
    }


    // 구독설정
    public void subscribe(NetworkView obj) {
        // this.output = output;
        this.view = obj;
        try {
            client.subscribe("/ds203/#", 0);
        }
        catch (MqttException e) {
            e.printStackTrace();
        }
    }

    // 구독해제
    public void unSubscribe() {
        try {
            client.unsubscribe("/ds203/#");
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("구독해제 실패");
        }
    }

    // 메시지보내기
    public void sendMessage(String msg) {
        try {
            MqttMessage message = new MqttMessage();
            message.setQos(0);
            message.setPayload( msg.getBytes() );
            client.publish("/ds203/test1", message);
        }
        catch(Exception e){
            e.printStackTrace();
            System.out.println("메시지 보내기 실패");
        }
    }

    @Override
    public void connectionLost(Throwable arg0) {
        System.out.println("연결이 끊김.");            
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken arg0) {
        System.out.println("메시전 전송 완료.");            
    }

    //메시지가 올것임 여기로 다른쪽에 찍어볼 것. view> NetworkView.java
    @Override
    public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
        //arg1를 mqttmessage 형태(byte)로 보내는 이유는 이외 형태로 보내 버리면 파일이나 이미지가 전송이 안됨.


        System.out.println("메시지 도착" + arg0);
        // arg0 = topic 채널

        // arg1 실제 메시지 => "{type:1, no:1000}" 이런 모양으로 보내는게 최적.
        // 꺼낼때 payload
        String msg = new String(arg1.getPayload(), "EUC-KR");

        // Json string으로 전송됨. 아래처럼 해서 꺼내줌.
        JSONObject json = new JSONObject(msg);
        int type = json.getInt("type"); // 1 파싱이라는 것임
        long no = json.getLong("no"); // 1000 파싱이라는 것임

        view.printItem(type, no);



        // String msg =  arg0 + " => " + new String(arg1.getPayload(), "EUC-KR") + "\n";
        // output.setText( msg + output.getText());
    }
}



NetworkView
mqtt networkview db 삼각관계

mymqtt 


일단
mqtt에서 바로 추가한다는 것에서 이건 놀람
원래 mqtt는 독립적인 존재이고, network에서 mqtt를 불러와야한다고 생각했었음.

but 이 방법은 선생님 본인이 좋지 않은 방법이라고 말씀하심.

내가 생각했던 것이 좋은 방향이라고 하심.

type과 no는 app에서 받아오는 것.(지금은 apptest에서 했음)

ex)

JSONObject jobj = new JSONObject();
jobj.put("type", 2);
jobj.put("no", item.getNo());
client.sendMessage(jobj.toString());



어제 했던 실시간 채팅은
1. app에서 view를 실행
2. view에서는 메세지를 받는 것(subscribe)와 보내는 것 동시 존재(sendMessage)
3. 이 과정은 view에서 mqtt로 메세지를 보내고, mqtt는 감지하여, 다시 화면 표기


오늘은 view 2개와 mqtt만 있음.(실습 문제)
1. itemview에서 메세지를 mqtt로 보내준다.(지금은 Apptest로 함.)
2. mqtt는 받고 networkview(mqtt 안에서 함수로 불러옴)가 감지하고 출력한다.
그러면 내가 해야할 일은
1. itemview에서 메세지 보내는 코드 sendmassage(지금은 Apptest로 함.)
2. networkview에서 mqtt 구독설정
3. mqtt에서 networkview 불러와서 print하기




오후일과

실시간 mqtt랑 view 연결하는 방법
1. view> NetworkView.java
    public NetworkView() {
        client.subscribe(this); // this => NetworkView의 객체
    }

2.  mqtt> MyMqttClient.java
private NetworkView view = null;

3. mqtt> MyMqttClient.java(subscribe)
this.view = obj;

4. mqtt> MyMqttClient.java
messageArrived 작성
//arg1를 mqttmessage 형태(byte)로 보내는 이유는 이외 형태로 보내 버리면 파일이나 이미지가 전송이 안됨.

5. mqtt> MyMqttClient.java
view.printItem(type, no);
json문서형식으로 보내서 빼내는 것임. 이것이 가장 좋은 방식

apptest에서
메세지 보내기 했음. 중요중요중요중요중요중요중요중요중요중요

app에서 network실행(감지하는 파일 networkview)
apptest에서 수동으로 보내줌.

 

원리------------------------------------------------------------------------

물품등록 예시
1.AppTest.java에서 iteminsert 실행
- Item 수동 입력
- Item 등록(결과값 ret 받아내기)
- ret값 1을 받았다면 등록 완료
- 등록 완료시 jobj 오브젝트를 만들기
jobj 오브젝트를 만드는 이유 : 2가지 정보를 한번에 보내기 위해서
- client.senMessage로 jobj 전송


NetworkView.java
- 구독설정 (화면표기하는 부분이나, 보여지는 곳에 설정 하는 듯)
- 실시간 물품 변경내역 출력하기 위해. 코드작성
    public NetworkView() {
        client.subscribe(this); // this => NetworkView의 객체
    }


mqtt
- private NetworkView view = null;
- 구독하기
    public void subscribe(NetworkView obj) {
        this.view = obj;}

messageArrived
- 메세지가 도착
- arg1(내용)을 payload로 꺼내줌
String msg = new String(arg1.getPayload(), "EUC-KR");
- JSONObject로 한번 더 꺼내줌(Json string으로 전송됨) 
JSONObject json = new JSONObject(msg);
- type은 int로, no은 long으로 변수 선언해주고 넣어줌)
int type = json.getInt("type"); // 1 파싱이라는 것임
long no = json.getLong("no"); // 1000 파싱이라는 것임

view로 선언된 NetworkView> prinItem 호출
view.printItem(type, no);

원리끝------------------------------------------------------------------------


< 북 ArraList로 단편적으로 쓰기 실습 >
8라인이 데이터 베이스처럼 쓰는 것

private List<Book> books = new ArrayList<>();


app은 북스뷰 실행

new BookView();


북 이건 형식인 모델임

북스토어
북에서 끌어다 쓰는 것이 아니라
양식만 가져와서 쓰는 것임.
private List<Book> books = new ArrayList<>();
null로 넣었다가 nullpoint가 떴었음.
왜 그런지 모르다가 선생님께 질문.
미리 Book의 형식으로 books를 만들고 books의 형태는 ArrayList 가변 배열

딱히 코드 설명 할 것은 없음.

북뷰
while문으로 하던 것 처럼. (작업인덱스 받아오기)

따로 함수를 작성 private void menu?
스캐너next로 책제목, 저자, 가격을 받아옴.
하던데로
book형식을 받아오고 거기에 split된 것들을 각각 title,writer,price에 넣어줌
그리고 bookstore.insertBook을 이용하여 집어 넣어줌.
그렇게 되면 bookstore의 insertBook이 반응
insertBook은 Book의 형태의 obj를 받고 있음.
BookStore에 만들어진 books라는 List 가변배열에 집어 넣어줌(add)
그리고 boolean으로 등록 성공인지 아닌지 판별 출력

원래 지금까지 했던 것과 service와 impl과 거의 비슷함.(그냥 같음)
service라는 interface는 생략된 것이고,
impl만 존재하니까 impl인 BookStore를 BookView로 끌어다 쓰는 것.

끌어다 쓰는 것도 그냥 한줄 추가 해주면 끝.
private BookStore bookstore = new BookStore();

메뉴는 Book이라는 모델을 불러오고 BookStore에 Book형식을 넣어 주는 것임.

다 완성하고 난뒤 기능이 되긴되는데 이상하게 출력되어서 
질문을 해보니
model에 ToString을 추가했어야함.

Book.java (model)

package com.example.exam_cls;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
// 제목, 저자, 가격
public class Book {
    
    // 1. 변수
    private String title = null;
    private String writer = null;
    private int price = 0;
    
    
    // 책이라는 기본적인 것을 생성하고 가고 싶음. 생성자 만들기
    
    // 새로운 생성자를 만들면 자동으로 만들어진 것이 사라짐
    public Book() {
    }


    // 새로운 생성자를 만들면 자동으로 만들어진 것이 사라짐
    // 생성자를 추가하면 default 생성자도 만들어야됨. (2개 이상)
    // 2. 생성자
    // public 무조건, 반환값x, 함수명이 클래스명과 같음.
    public Book(String title, String writer, int price) {
        this.title = title;
        this.writer = writer;
        this.price = price;
    }
    


    // 3. 메소드 getter / setter

    public String getTitle() {
        return title;
    }


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

    public String getWriter() {
        // 문자를 내보내줌
        return writer;
    }

    public void setWriter(String writer) {
        // 문자 하나가 들어와야함. 이건 반환x
        this.writer = writer;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
    // 할인된 가격으로 반환하기
    // ex) 10000 0.25 -> 7500
    // ex) 20000 0.5  -> 10000 
    public float getDiscount(float rate){
        float tmp = this.price - (this.price * rate);
        return tmp;
    }
}

 

BookStore.java

package com.example.exam_cls;

import java.util.ArrayList;
import java.util.List;

public class BookStore{
    
    private List<Book> books = new ArrayList<>();

    // books에 책 추가
    public void insertBook(Book obj){
    // public boolean insertBook(Book obj){
        boolean ret = this.books.add(obj);
        if(ret == true){
            System.out.println("등록 성공");
        }
        else{
            System.out.println("등록 실패");
        }
        // return ret;
    }

    // books에 책 삭제(3)
    public void deleteBook(){
        Book ret = books.remove(books.size()-1);
        if(ret != null){
            System.out.println("삭제 성공");
        }
        else{
            System.out.println("삭제 실패");
        }
    }

    // 책 보유현황
    public List<Book> getBooks(){
        // System.out.println(books);
        return books;
    }

    //BookView.java에서 1등록 books
    //BookView.java에서 2삭제 books
    //BookView.java에서 3목록 books
    //BookView.java에서 4목록 books 책제목만
    //BookStore와 BookView를 Q&A에 저장
}

BookView.java

package com.view;

import java.util.List;
import java.util.Scanner;

import com.example.exam_cls.Book;
import com.example.exam_cls.BookStore;

public class BookView {
    private BookStore bookstore = new BookStore();
    private Scanner scanner = new Scanner(System.in);


    public BookView(){
       while(true) {
            System.out.println("1.책 등록");
            System.out.println("2.책 삭제");
            System.out.println("3.책 리스트");
            System.out.println("4.책 리스트 제목만");
            System.out.println("0.종료");
            System.out.print("메뉴 선택 => ");
            int menu = scanner.nextInt();
            if(menu == 0){
                break;
            }
            else if(menu == 1) {
                menu1();
            }
            else if(menu == 2) {
                menu2();
            }
            else if(menu == 3) {
                menu3();
            }
            else if(menu == 4) {
                menu4();
            }
        }
    }
    private void menu1(){
        scanner.nextLine(); // buffer비우기
        System.out.print("책 제목,저자,가격 입력 => ex)피타고라스,23,23 ");
        String[] arr = scanner.next().split(",");
        Book book = new Book();
        book.setTitle(arr[0].trim());
        book.setWriter(arr[1].trim());
        book.setPrice(Integer.valueOf(arr[2].trim()));
        bookstore.insertBook(book);
    }
    private void menu2(){
        // scanner.nextLine(); // buffer비우기
        System.out.println("최근 것이 지워짐");
        // Book book = new Book();
        // book.setTitle(scanner.next());
        bookstore.deleteBook();
    }
    private void menu3(){
        List<Book> list = bookstore.getBooks();
        for(Book tmp : list){
            System.out.println(tmp.toString());
        }
    }
    //BookView.java에서 4목록 books 책제목만
    private void menu4(){
        List<Book> list = bookstore.getBooks();
        for(Book tmp : list){
            System.out.println(tmp.getTitle().toString());
        }
    }
}