본문 바로가기

Java

[Java] 39

실습(영화 순위 관리 프로그램_(1. 영화 추가하기 & 4. 영화 검색하기))

1. 영화 추가하기

- MovieDAO.java(Data Access Object)에서 영화 정보를 추가하는 메소드를 생성한다.

// 추가하기 : 관객수에 따라 알맞은 랭킹 찾아서 추가하기

	public void add(MovieDTO dto) throws IOException {
		// 매개변수로 받아온 dto 객체에는 추가하고 싶은 영화에 대한 제목, 개봉일, 관객수, 수익, 상영관수가 들어있다.
		// 내가 삽입할 영화가 들어갈 위치를 찾아야 한다.
		
		// targetView : 내가 추가하고 싶은 영화의 관객수
		int targetView = Integer.parseInt(dto.getView());
		
		BufferedReader br = DBConnection.read();
		String contents = "";
		String line = "";
		int rank = 0;  // 내가 삽입할 영화의 순위를 알아낼 변수
		
		while((line = br.readLine()) != null) {
			String[] temp = line.split("\t");
			// temp[4] : "17,613,682"
			// temp[4].replaceAll(",", "")) : "17613682"
			// movieView : 기존에 존재하던 영화의 관객수
			int movieView = Integer.parseInt(temp[4].replaceAll(",", ""));
			rank++;
			
			if(targetView > movieView) {
				break;
			}
			
			contents += line + "\n";
			
		}
		
		// while문이 끝나면 삽입할 위치(만약 내가 삽입할 위치가 맨 마지막이라면 rank를 1 증가시킨다)
		if(line == null) rank++;
		
		contents += rank +"\t" + dto.getTitle() + "\t" + dto.getDate() + 
				"\t" + dto.getRevenue() + "\t" + dto.getView() + "\t" + dto.getScreen()+"\n";
		
		// line에는 기존 영화 정보가 들어있기 때문에
		while(line != null) {  // 바로 한 줄을 읽어오지 않는다
			// 삽입한 이후부터는 랭킹이 1위씩 밀려야하기 때문에 필요한 값은 랭킹 이후 \t부터 끝까지이다.
			rank++;
			contents += rank + line.substring(line.indexOf("\t")) + "\n";
			line = br.readLine();
		}		
		br.close();

		BufferedWriter bw = DBConnection.write();
		bw.write(contents);
		bw.close();
		
	}

- View.java에서 "1. 영화 추가하기"를 실행하는 코드를 작성한다.

if(choice == 1) {
	MovieDTO dto = new MovieDTO();

	System.out.print("제목 : ");
	dto.setTitle(sc.nextLine());

	System.out.print("개봉일 : ");
	dto.setDate(sc.nextLine());

	System.out.print("관객수 : ");
	dto.setView(sc.nextLine());

	System.out.print("상영관수 : ");
	dto.setScreen(sc.nextLine());

	System.out.print("수익 : ");
	dto.setRevenue(sc.nextLine());
		
	dao.add(dto);			
}
​

1. 영화 추가하기 결과

 

추가한 영화 적용 확인

2. 영화 수정하기

- MovieDAO.java(Data Access Object)에서 영화 정보를 수정하는 메소드를 생성한다.

public boolean update(int rank, String title) throws IOException {
		if(rank < 1 || rank > getLastRank()) {
			return false;
		}
		
		BufferedReader br = DBConnection.read();
		String line = "";
		String contents = "";
		
		for (int i = 0; i < rank - 1; i++) {
			line = br.readLine();
			contents += line + "\n";
		}
		
		line = br.readLine(); // 수정할 문장
		String[] temp = line.split("\t");
		temp[1] = title;
		contents += String.join("\t", temp) + "\n";
		
		while((line = br.readLine()) != null) {
			contents += line + "\n";
		}
		
		br.close();
		
		BufferedWriter bw = DBConnection.write();
		bw.write(contents);
		bw.close();
		
		return true;
}

- View.java에서 "2. 영화 수정하기"를 실행하는 코드를 작성한다.

if(choice == 2) {
	System.out.print("수정할 랭킹 >> ");
	choice = Integer.parseInt(sc.nextLine());

	System.out.print("수정할 제목 >> ");
	String title = sc.nextLine();

	if(dao.update(choice, title)) {
		System.out.println("수정 성공");
	} else{
		System.out.println("랭킹을 다시 확인해주세요");
	}
		
}
 
2. 영화 수정하기 결과

3. 영화 삭제하기

- MovieDAO.java(Data Access Object)에서 영화 정보를 삭제하는 메소드를 생성한다.

public boolean  remove(int rank) throws IOException {
		
	// 랭킹이 제대로 입력되지 않았을 경우
	if(rank < 1 || rank > getLastRank()) {
		return false;
	}
	
	BufferedReader br = DBConnection.read();
	String contents = "";
	String line = "";
		
	for(int i = 0; i < rank-1; i++) {
		line = br.readLine();
		contents += line + "\n";
	}
	
	// 반복문이 끝나면 내가 삭제하고자 하는 영화 위쪽의 값들이 contents에 들어가게 된다.
	br.readLine();  // 내가 삭제하고자 하는 영화는 contents에 연결하지 않는다.
	
	while((line = br.readLine()) != null) {
		// line : 기존 영화 한 줄
		// line.split("\t") : \t를 기준으로 쪼갠 배열
		// line.split("\t")[0] : 순위가 들어있는 문자열
		// Integer.parseInt(line.split("\t")[0]) : int값으로 바뀐 순위
		// Integer.parseInt(line.split("\t")[0]) - 1 : 수정된 순위
		
		contents += Integer.parseInt(line.split("\t")[0]) - 1 + line.substring(line.indexOf("\t")) + "\n";
	}
	
	br.close();
	
	BufferedWriter bw = DBConnection.write();
	bw.write(contents);
	bw.close();
	
	return true;
}

- View.java에서 "3. 영화 삭제하기"를 실행하는 코드를 작성한다.

if(choice == 3) {
	System.out.print("삭제할 랭킹 >> ");

	if(dao.remove(Integer.parseInt(sc.nextLine()))) {
		System.out.println("삭제 성공");

	} else {
		System.out.println("랭킹을 다시 확인해주세요");
	}
	
}
 
3. 영화 삭제하기 결과

※ 전체코드(View.java)

import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

import dao.MovieDAO;
import dto.MovieDTO;

public class View {
	public static void main(String[] args) throws IOException {

		Scanner sc = new Scanner(System.in);
		MovieDAO dao = new MovieDAO();
		
		while(true) {
			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.print("입력 >> ");
			int choice = Integer.parseInt(sc.nextLine());
			
			if(choice == 6) {
				break;
			} else if(choice == 1) {
				MovieDTO dto = new MovieDTO();
				System.out.print("제목 : ");
				dto.setTitle(sc.nextLine());
				System.out.print("개봉일 : ");
				dto.setDate(sc.nextLine());
				System.out.print("관객수 : ");
				dto.setView(sc.nextLine());
				System.out.print("상영관수 : ");
				dto.setScreen(sc.nextLine());
				System.out.print("수익 : ");
				dto.setRevenue(sc.nextLine());
				
				dao.add(dto);
				
				
			} else if(choice == 2) {
				System.out.print("수정할 랭킹 >> ");
				choice = Integer.parseInt(sc.nextLine());
				System.out.print("수정할 제목 >> ");
				String title = sc.nextLine();
				if(dao.update(choice, title)) {
					System.out.println("수정 성공");
				} else{
					System.out.println("랭킹을 다시 확인해주세요");
				}
				
				
			} else if(choice == 3) {
				System.out.print("삭제할 랭킹 >> ");
				if(dao.remove(Integer.parseInt(sc.nextLine()))) {
					System.out.println("삭제 성공");
				}else {
					System.out.println("랭킹을 다시 확인해주세요");
				}
				
				
			} else if(choice == 4) {
				System.out.println("1. 랭킹으로 검색");
				System.out.println("2. 영화제목으로 검색");
				System.out.print("입력 >> ");
				choice = Integer.parseInt(sc.nextLine());
				if(choice == 1) {
					System.out.print("랭킹 입력 >> ");
					choice = Integer.parseInt(sc.nextLine());
					MovieDTO res = dao.selectByRank(choice);
					if(res == null) {
						System.out.println("검색 실패 : 순위를 다시 입력하세요");
					} else {
						System.out.println("-----검색 결과-----");
						System.out.println(res.getRank() + "위 영화");
						System.out.println("제목 : " + res.getTitle());
						System.out.println("개봉일 : " + res.getDate());
						System.out.println("관객수 : " + res.getView());
						System.out.println("상영관수 : " + res.getScreen());
						System.out.println("수익 : " + res.getRevenue());
					}
					
				} else if(choice == 2) {
					System.out.print("제목 입력 >> ");
					String title = sc.nextLine();
					System.out.println("-----검색 결과-----");
					
					for(MovieDTO movie : dao.selectByTitle(title)) {
						System.out.println("순위 : " + movie.getRank());
						System.out.println("제목 : " + movie.getTitle());
						System.out.println("개봉일 : " + movie.getDate());
						System.out.println("관객수 : " + movie.getView());
						System.out.println("상영관수 : " + movie.getScreen());
						System.out.println("수익 : " + movie.getRevenue());
						System.out.println("---------------");
					}
				
				} else {
					System.out.println("잘못 입력했습니다");
				}
				
				
			} else if(choice == 5) {
				ArrayList<MovieDTO> list =  dao.selectAll();
				System.out.println("-----전체 영화 정보-----");
				for (MovieDTO dto : list) {
					System.out.println("[" + dto.getRank() + "]--" + dto.getTitle());
					System.out.println("|개봉일 : " + dto.getDate());
					System.out.println("|순수익 : " + dto.getRevenue());
					System.out.println("|관객수 : " + dto.getView());
					System.out.println("|상영관 : " + dto.getScreen());
					System.out.println("---------------");
				}
				
				
			} else {
				System.out.println("잘못 입력했습니다");
			}
			
		}
	}

}

※ 전체코드(MovieDAO.java)

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;

import dto.MovieDTO;

public class MovieDAO {
	public ArrayList<MovieDTO> selectAll() throws IOException {
		ArrayList<MovieDTO> list = new ArrayList<>();
		BufferedReader br = DBConnection.read();
		String line = "";

		while((line = br.readLine()) != null) {
			// line에는 영화 한 편에 대한 정보가 들어있다
			String[] temp = line.split("\t");
			MovieDTO dto = new MovieDTO();
			dto.setRank(Integer.parseInt(temp[0]));
			dto.setTitle(temp[1]);  // dto.title = temp[1];
			dto.setDate(temp[2]);
			dto.setRevenue(temp[3]);
			dto.setView(temp[4]);
			dto.setScreen(temp[5]);
			list.add(dto);
		}
		br.close();
		return list;
	}
	
	
	// 마지막 영화 랭킹을 return 하는 메소드
	public int getLastRank() throws IOException{
		
		BufferedReader br = DBConnection.read();
		int rank = 0;
		String line = "";
		
		while((line = br.readLine()) != null) {
			rank++;
		}
		br.close();
		return rank;
	}
	
	
	// 랭킹으로 영화 검색하기
	public MovieDTO selectByRank(int rank) throws IOException {
		
		// 없는 랭킹을 입력했을 때 버그 잡아주기
		if(rank < 1 || rank > getLastRank()) {
			return null;
		}
		
		BufferedReader br = DBConnection.read();
		String line = "";
		
		for(int i = 0; i < rank; i++) {
			line = br.readLine();
		}
		br.close();
		
		// 반복문이 끝나고 나면 line에는 내가 필요한 영화 한줄이 들어있다
		String[] temp = line.split("\t");  
		
		// 쪼갠 배열로 return 하여 view를 만드는 사람이 원하는대로 사용해도 된다.		
		MovieDTO dto = new MovieDTO();
		dto.setRank(Integer.parseInt(temp[0]));
		dto.setTitle(temp[1]);
		dto.setScreen(temp[5]);
		dto.setView(temp[4]);
		dto.setDate(temp[2]);
		dto.setRevenue(temp[3]);
		return dto;
	}
	
	
	// 제목으로 영화 검색하기
	public ArrayList<MovieDTO> selectByTitle(String title) throws IOException{
		ArrayList<MovieDTO> list = new ArrayList<MovieDTO>();
		BufferedReader br = DBConnection.read();
		String line = "";
		
		while((line = br.readLine()) != null) {
			String[] temp = line.split("\t");
		
			// 영화제목은 temp[1]에 들어있다
			if(temp[1].equals(title)) {
				// line에는 원하는 영화 정보가 들어있다.
				MovieDTO dto = new MovieDTO();
				dto.setRank(Integer.parseInt(temp[0]));
				dto.setTitle(temp[1]);
				dto.setDate(temp[2]);
				dto.setRevenue(temp[3]);
				dto.setView(temp[4]);
				dto.setScreen(temp[5]);
				list.add(dto);
			}
		}
		br.close();
		return list;
	}
	
	
	// 추가하기 : 관객수에 따라서 알맞은 랭킹 찾아서 추가하기
	public void add(MovieDTO dto) throws IOException {		
		// targetView : 내가 추가하고 싶은 영화의 관객수
		int targetView = Integer.parseInt(dto.getView());
		BufferedReader br = DBConnection.read();
		String contents = "";
		String line = "";
		int rank = 0;  // 내가 삽입할 영화의 순위를 알아낼 변수
		
		while((line = br.readLine()) != null) {
			String[] temp = line.split("\t");
			int movieView = Integer.parseInt(temp[4].replaceAll(",", ""));
			rank++;
			
			if(targetView > movieView) {
				break;
			}
			contents += line + "\n";
		}
		
		// while문이 끝나면 삽입할 위치(만약 내가 삽입할 위치가 맨 마지막이라면 rank를 1 증가시킨다)
		if(line == null) rank++;
		
		contents += rank +"\t" + dto.getTitle() + "\t" + dto.getDate() + 
				"\t" + dto.getRevenue() + "\t" + dto.getView() + "\t" + dto.getScreen()+"\n";
		
		while(line != null) {  // 바로 한 줄을 읽어오지 않는다
			// 삽입한 이후부터는 랭킹이 1위씩 밀려야하기 때문에 필요한 값은 랭킹 이후 \t부터 끝까지이다.
			rank++;
			contents += rank + line.substring(line.indexOf("\t")) + "\n";
			line = br.readLine();
		}	
		br.close();
		BufferedWriter bw = DBConnection.write();
		bw.write(contents);
		bw.close();
	}
	
	
	// 삭제하기 : 랭킹으로 삭제하기
	public boolean  remove(int rank) throws IOException {
		
		// 랭킹이 제대로 입력되지 않았을 경우
		if(rank < 1 || rank > getLastRank()) {
			return false;
		}
		
		BufferedReader br = DBConnection.read();
		String contents = "";
		String line = "";
		
		for(int i = 0; i < rank-1; i++) {
			line = br.readLine();
			contents += line + "\n";
		}
		
		br.readLine();  // 내가 삭제하고자 하는 영화는 contents에 연결하지 않는다.
		
		while((line = br.readLine()) != null) {
			contents += Integer.parseInt(line.split("\t")[0]) - 1 + line.substring(line.indexOf("\t")) + "\n";
		}
		br.close();
		BufferedWriter bw = DBConnection.write();
		bw.write(contents);
		bw.close();
		return true;
	}
	
	
	// 수정하기 : 랭킹으로 영화 제목 수정하기
	public boolean update(int rank, String title) throws IOException {
		if(rank < 1 || rank > getLastRank()) {
			return false;
		}
		
		BufferedReader br = DBConnection.read();
		String line = "";
		String contents = "";
		
		for (int i = 0; i < rank - 1; i++) {
			line = br.readLine();
			contents += line + "\n";
		}
		
		line = br.readLine(); // 수정할 문장
		String[] temp = line.split("\t");
		temp[1] = title;
		contents += String.join("\t", temp) + "\n";
		
		while((line = br.readLine()) != null) {
			contents += line + "\n";
		}
		
		br.close();
		BufferedWriter bw = DBConnection.write();
		bw.write(contents);
		bw.close();
		return true;
	}

}

'Java' 카테고리의 다른 글

[Java] 38  (0) 2022.02.12
[Java] 37  (0) 2022.02.10
[Java] 36  (0) 2022.02.08
[Java] 35  (0) 2022.02.06
[Java] 34  (0) 2022.02.05