[til 013] 컬렉션 2

김동현·2023년 8월 1일
0

til

목록 보기
25/53
package edu.kh.collection.model.service;

import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

import edu.kh.collection.model.vo.Book;

public class BookService {


private Scanner sc = new Scanner(System.in);

private List<Book> bookList = new LinkedList<Book>();
private List<Book> bookList2 = new LinkedList<Book>();

public BookService() {
	bookList.add(new Book("수학의정석", "홍성대", 30000, "미상"));
	bookList.add(new Book("미술", "피카소", 1360000, "미상"));
	bookList.add(new Book("영어", "미국", 50000, "미상"));
}

public void dp () {
	int input = 0;
	
	do {
		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("0. 종료");
		System.out.print("\n메뉴 번호 선택 : ");
		
		try {
			input = sc.nextInt();
			System.out.println();
			
			switch(input) {
			case 1: System.out.println(addBook()); break;
			case 2: selectAll(); break;
			case 3: updateBook(); break;
			case 4: System.out.println(removeBook()); break;
			case 5: System.out.println(likeGood()); break;
			case 6: System.out.println(removeLike()); break;
			case 7: likeAll(); break;
			default : System.out.println("잘못입력했습니다.");
			}
			
		} catch(InputMismatchException e) {
			System.out.println("\n잘못입력하셨습니다.");
			sc.nextLine();
			input = -1;
		}
	
		
		
		
	} while(input != 0);
			
	
}

public String addBook() {
	System.out.print("도서명 : ");
	sc.nextLine();
	String bookName = sc.nextLine();
	
	System.out.print("저자명 : ");
	
	String author = sc.nextLine();
	System.out.print("가격 : ");
	int won = sc.nextInt();
	System.out.print("출판사 : ");
	sc.nextLine();
	String hs = sc.nextLine();
	
	if (bookList.add(new Book(bookName, author, won, hs))) {
		return "성공";
		
	} else {
		return "실패";
		
	}
	
}

public void selectAll() {
	System.out.println("=====도서목록=====");
	if (bookList.isEmpty()) {
		System.out.println("정보가 없습니다.");
		return;
		
	}
	int index = 0;
	for (Book bk : bookList) {
		System.out.print(index++ +"번 도서 : ");
		System.out.println(bk);
	} return;
}

public String updateBook() throws InputMismatchException{
	System.out.println("=====도서정보수정=====");
	System.out.println("수정할 도서명의 번호를 입력해주세요");
	System.out.print("번호 : ");
	int serch1 = sc.nextInt();
	System.out.println(bookList.get(serch1));
	int input = 0;
	int index = 0;
	for (int i = 0; i < bookList.size(); i++) {
		if (bookList.get(i).getBookName().equals(serch1)) {
			index = i;
		
		}
	}
	if (input >= bookList.size() || input < 0) {
		return "정보가 없습니다";
	}
	
	do {
		System.out.println("수정할 정보를 선택하세요");
		System.out.println("1. 도서명");
		System.out.println("2. 저자명");
		System.out.println("3. 가격");
		System.out.println("4. 출판사");
		System.out.println("0. 종료");
		System.out.print("입력 : ");
		input = sc.nextInt();
		
		switch(input) {
		case 1: 
		System.out.print("수정할 도서명 : ");
		sc.nextLine();
		String bookName = sc.nextLine();
		bookList.get(index).setBookName(bookName);
		System.out.println("수정완료");
		break;
		case 2: 
		System.out.print("수정할 저자명 : ");
		sc.nextLine();
		String author = sc.nextLine();
		bookList.get(index).setAuthor(author);
		System.out.println("수정완료");
		break;
		case 3: 
		System.out.print("수정할 가격 : ");
		int won = sc.nextInt();
		bookList.get(index).setWon(won);
		System.out.println("수정완료");
		break;
		case 4: 
		System.out.print("수정할 출판사명 : ");
		sc.nextLine();
		String hs = sc.nextLine();
		bookList.get(index).setHs(hs);
		System.out.println("수정완료");
		break;
		default : System.out.println("입력오류");
		}
	} while (input != 0);
	
	return "";
	
	
}

public String removeBook() {
	System.out.print("제거할 책 번호 : ");
	int input = sc.nextInt();
	
	if (bookList.isEmpty()) {
		return "정보없음";
	} else if (input <0) {
		return "0보다 큰 수를 입력하세요.";
				
	} else if ( input >= bookList.size()) {
		return "범위 초과";
	} else {
		System.out.print("정말 제거하시겠습니까? (Y/N) : ");
		char input2 = sc.next().toUpperCase().charAt(0);
		
		if ( input2 == 'Y') {
			Book temp = bookList.remove(input);
			return temp.getBookName()+"책 정보가 제거되었습니다";
			
		} else {
			return "종료...";
		}
	}
	
	
		
}
public String likeGood () throws InputMismatchException{
	ArrayList<Integer> arr = new ArrayList<Integer>();
	// 가변되는 배열 설정
	// 책번호 입력 쌓이게하고
	// 이걸 토대로 불러와야 연동 list.get(i).getbooknum.equals(arr.(j))
	

	
	System.out.println("좋아요 목록에 등록할 책 번호 : ");
	int input = sc.nextInt();
	
	if (input <0) {
		return "0보다 큰 수를 입력하세요.";
				
	} else if ( input >= bookList.size()) {
		return "범위 초과";
	} else {
		bookList2.add(bookList.get(input));
		return bookList.get(input).getBookName()+ "이등록되었습니다";
	}
	
	
			
}

public String removeLike() throws InputMismatchException{
	System.out.println("좋아요 목록을 우선 확인해주세요");
	System.out.println("좋아요 목록에서 제거할 책 번호 : ");
			
	int input = sc.nextInt();
	
	if (bookList.isEmpty()) {
		return "정보없음";
	} else if (input <0) {
		return "0보다 큰 수를 입력하세요.";
				
	} else if ( input >= bookList2.size()) {
		return "범위 초과";
	} else {
		System.out.print("정말 제거하시겠습니까? (Y/N) : ");
		char input2 = sc.next().toUpperCase().charAt(0);
		
		if ( input2 == 'Y') {
			Book temp = bookList2.remove(input);
			return temp.getBookName()+"책 정보가 제거되었습니다";
			
		} else {
			return "종료...";
		}
	}
	
	
		
}
public void likeAll() {
	System.out.println("=====좋아요 도서목록=====");
	if (bookList2.isEmpty()) {
		System.out.println("정보가 없습니다.");
		return;
		
	}
	int index = 0;
	for (Book bk : bookList2) {
		System.out.print(index++ +"번 도서 : ");
		System.out.println(bk);
	} return;
}

}

package edu.kh.collection.model.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import edu.kh.collection.model.vo.Member;

public class MapService {

// Map : Key 와 Value 한 쌍이 데이터가 되어 이를 모아둔 객체

// - Key를 모아두면 Set의 특징 (중복 X)
// - Value를 모아두면 List의 특징 (중복 O)

public void ex1() {
	
	// HashMap<K, V> : Map의 자식 클래스 중 가장 대표되는 Map
	
	Map<Integer, String> map = new HashMap<Integer, String>();
	
	// Map.put(Integer Key, String Value) : 추가
	map.put(1, "홍길동");
	map.put(2, "고길동");
	map.put(3, "제갈길동");
	map.put(4, "박길동");
	map.put(5, "이길동");
	map.put(5, "최길동");// Key중복 {1=홍길동, 2=고길동, 3=제갈길동, 4=박길동, 5=최길동} 5번이 최길동으로 덮어쓰임
						// 중복허용 X, 대신 Value 덮어쓰기
	map.put(6, "최길동"); // Value 중복 허용
	System.out.println(map); // map.toString() 오버라이딩 되어있음
	
}

public void ex2() {
	
	// Map 사용 예제
	
	// VO(값 저장용 객체)는 특정 데이터 묶음의 재사용이 많은 경우 주로 사용
	// -> 재사용이 적은 VO는 오히려 코드 낭비
	// -> Map을 이용해서 VO와 비슷한 코드를 작성할 수 있다.
	
	// 1) VO 버전
	Member mem = new Member();
	
	// 값세팅
	mem.setId("user01");
	mem.setPw("pass01");
	mem.setAge(30);
	
	// 값 출력
	System.out.println(mem.getId());
	System.out.println(mem.getPw());
	System.out.println(mem.getAge());
	
	System.out.println("=====================");
	
	// 2) Map버전
	Map<String, Object> map = new HashMap<String, Object>();
	// value가 Object 타입 == 어떤 객체든 Value에 들어올 수 있다.
	
	// 값 세팅
	map.put("id", "user02");
	map.put("pw", "pass2");
	map.put("age", 25);
	
	// 값 출력
	System.out.println(map.get("id"));
	System.out.println(map.get("pw"));
	System.out.println(map.get("age"));
	
	System.out.println("======================");
	
	// ** Map에 저장된 데이터 순차적으로 접근하기 **
	
	// Map에서 Key만 모아두면 Set의 특징을 가진다.
	// -> 이를 활용 할 수 있도록 Map에서
	//		keySet() 메서드 제공
	// -> Key만 모아서 Set으로 제공
	
	Set<String> set = map.keySet();
	
	System.out.println("keySet(): " + set);
	
	// 향상된 for 문
	for ( String key : set) {
		System.out.println(map.get(key));
	}
	// map 에 저장된 데이터가 많거나
	// 어떤 key가 있는지 불분명할때
	// 또는 map 에 저장된 모든 데이터에 접근해야할 때
	// keySet() + 향상된 for문 코드 사용
	
}

public void ex3() {
	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
	
	for (int i =0; i<10; i++) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		// map에 데이터 추가
		
		map.put("id",  "user0"+i);
		
		// Map을 List 추가
		list.add(map);
	}
	// for 문 종료시 list에 10개의 Map 객체가 추가되어있다.
	
	for ( Map<String, Object> temp : list) {
		System.out.println(temp.get("id"));
	}
}


}

오늘 한것들. 어제에 이어 map에 관해서도 배웠다.
어제 했던것들을 토대로 연습문제를 풀어보며 내가 만든 코드와 강사님의 코드를 비교해보며 군더더기가 많이 제거될 수 있음을 알았다.

list와 map set value 의 차이점들(중복의 유무등)과 이것들의 기능들을 알아보았다.

혼자 작성하던중 숫자를 세개씩 끊어 ','를 중간에 입력하는 방법도 있다는걸 알게되었다.

list에 대해서도 햇갈리던 부분을 더 잘 알게되었다.

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

private List<Book> favList = new ArrayList<Book>();
for(Book temp : library) {
		if(temp.getBookNum() == input) {
			favList.add(temp);
            

library와 favList 모두 Book 객체를 다루는 리스트. library는 모든 책을 저장하는 리스트이며, favList는 library에서 특정 조건을 만족하는 즐겨찾기한 책들만을 저장하는 리스트이다.

위의 코드 예시에서는 library 리스트에서 특정 조건을 만족하는 Book 객체들을 찾아 favList에 추가하고 있다. 이렇게 하면 favList에는 library에 있는 일부 Book 객체들이 포함되게 된다. 즉, library와 favList는 공통된 Book 객체를 다루지만, favList는 library에서 선택된 일부 Book 객체들로 구성된다.

0개의 댓글

관련 채용 정보