본문 바로가기

Java

Java(11) - Theater 예제(극장 좌석 예약 프로그램 만들기)

728x90
반응형

<목차>

1) Theater 예제

   1-1) 요구 조건

   1-2) 예제 풀이

 

 

 

 

 

1) Theater 예제

  • 기본 생성자 : new 키워드로 인스턴스를 생성할 때마다 자동으로 실행됨!
  • 명시적 생성자 : 사용자가 지정한 값으로 값을 초기화해 줌!
  • 생성자는 Return 값이 없기에 데이터 타입(void, int, String 등)을 지정하지 않아야 함!
  • Java에서의 기본값  =>  참조형 데이터 타입의 기본값: Null, Int의 기본값: 0

 

 

1-1) 요구 조건

/*
	 * 극장 좌석 예약 프로그램 만들기
		  1. Theater, Theater_Method 두개의 클래스를 생성하여 기능을 분리한다.
		  2. Theater클래스에서는 main()메서드를 포함하며 출력문구를 사용하지 않는다. 
		  3. Theater_Method의 멤버변수 혹은 멤버메서드를 호출하여 출력문구 및 로직을 처리한다.
		  
		  - Theater
		     main() : 메뉴를 종료를 선택하기 전까지 반복하여 보여주고 선택된 번호에 따라 기능을 수행한다.
		  
		  - Theater_Method
		  	   멤버 변수
		  		외부에서의 데이터의 접근을 막기 위해 다음과 같이 선언한다.
		  		private int[][] seats = new int[7][7];
		  
		  	   멤버 메서드
		  		1) printMenu() : 극장 좌석의 예약 현황을 보여준다.
		  		2) inputCnt() : 예약할 좌석의 개수를 입력받아 반환한다.
		  		3) seatInfo() : 2차원배열을 이용하여 극장 좌석의 예약현황을 보여준다.
		  				(예약 X : 1, 예약 O : 0)
		  		4) reservationSeats(int cnt) : 예약할 좌석의 개수를 매개변수(parameter)로 받고
		  				그 횟수만큼 행과 열의 값을 입력받는다.
		  				a. 예약이 되어 있지 않을 경우(해당 행과 열의 값이 0일때), 
		  				      해당 행과 열의 값을 1로 변경하고, "예약되었습니다."라는 문구를 출력한다.
		  				b. 예약이 되어 있는 경우(해당 행과 열의 값이 0일때),
		  				   "x행x열은 예약된 좌석입니다."라는 문구를 출력하고, 다시 행과 열을 입력 받는다.
*/

 

 

 

1-2) 예제 풀이

패키지 chapter08.classPart

Theater.class

package chapter08.classPart;

import java.util.Scanner;

public class Theater {

	public static void main(String[] args) {
		Theater_Method tm = new Theater_Method(); // 인스턴스 생성
		Scanner scan = new Scanner(System.in);
		
		int num = 0;    // 좌석 정보, 좌석 예약, 프로그램 종료 처리를 위한 변수
		int cnt = 0;	// 예약 좌석 개수
		
		tm.printText(1);
		while(true) {
			tm.printMenu();   // tm 클래스(인스턴스)의 printMenu 메서드를 호출하는 코드
			num = scan.nextInt();
			
			switch(num) {
			    case 1:      // 좌석 정보를 출력
			    	tm.seatInfo();
			    	break;
			    case 2:      // 좌석 예약을 실행
			    	cnt = tm.inputCnt();
			    	tm.reservationSeats(cnt);
			    	break;
			    case 0:      // 프로그램 종료
			    	tm.printText(2);
			    	System.exit(0);
			    default:
			    	// 입력 1, 2, 0이 아닐 경우 메시지 출력
			    	tm.printText(3);
			    	break;
			}
		}

	}

}

 

 

Theater_Method.class

package chapter08.classPart;

import java.util.Scanner;

public class Theater_Method {
	// 멤버 변수
	private int[][] seats = new int[7][7];
	
	Scanner sc = new Scanner(System.in);
	
	/*
	// 첫 실행 시에만 맨 상단에 빨간색 글씨로 "극장 좌석 예약 프로그램"이라는 문구를 출력하기 위한 코드
	public Theater_Method() {
		System.err.println("극장 좌석 예약 프로그램");
	}
	*/

	public void printMenu() {
		System.out.println();
		System.out.println("메뉴의 번호를 선택해 주세요.");
		System.out.println("===========================");
		System.out.println("1. 좌석 확인");
		System.out.println("2. 좌석 예약");
		System.out.println("0. 종    료");
		System.out.println("===========================");
		System.out.print("번호를 선택하세요 : ");
	}
	
	// 좌석정보를 출력하는 코드
	public int[][] seatInfo() {
		System.out.println();
		System.out.println("* 좌석 예약 정보");
		System.out.println("-----------------------------");
		System.out.println("   1 2 3 4 5 6 7");
		System.out.println("-----------------------------");
		
		for (int i = 0; i < seats.length; i++) {
			System.out.print((i+1) + "| ");
			
			for (int j = 0; j < seats[i].length; j++) {
				System.out.print(seats[i][j] + " ");
			}
			
			System.out.println();
		}
		
		return seats;
	}
	
	public int inputCnt() {
		System.out.print("몇 개의 좌석을 예약하시겠습니까? ");
		int seatNum = sc.nextInt();
		
		return seatNum;
	}
	
	public void reservationSeats(int seatNum) {
		while(seatNum > 0) {
			/*
			   seatRow와 seatCol의 인덱스가 초기 0 ~ 6까지로 설정이 되어있기에 "ArrayIndexOutOfBoundsException"
			   에러가 발생하므로 이를 해결하기 각 예약좌석(7행 7열)의 행, 열 입력값에 대해 1을 빼서 최대 인덱스인 6을
			   넘지 않도록 맞춰주는 처리를 함!!
			*/
			System.out.print("예약할 좌석의 행 : ");
			int seatRow = sc.nextInt() - 1;
			System.out.print("예약할 좌석의 열 : ");
			int seatCol = sc.nextInt() - 1;

			if (seats[seatRow][seatCol] == 0) {
				seats[seatRow][seatCol] = 1;
				
				System.out.println("예약되었습니다.");
				seatNum--;
			} else {
				System.out.println((seatRow+1) + "행 " + (seatCol+1) + "열은 예약된 좌석입니다.");
			}
		}
	}

	public void printText(int i) {
		if (i == 1) {
			System.out.println("극장 좌석 예약 프로그램");
		} else if (i == 2) {
			System.out.println("프로그램 종료");
		} else if (i == 3) {
			System.out.println("잘 못 입력함!!");
		}
	}
	
}

 

 

 

 

 

 

 

 

 

 

 

<교수님 Version>

Theater.class

package chapter07.class_part1;

import java.util.Scanner;

public class Theater {

	public static void main(String[] args) {

		/*
		 * 극장 좌석 예약 프로그램 만들기
		 * 		1. Theater, Theater_Method 두개의 클래스를 생성하여 기능을 분리한다.
		 * 		2. Theater클래스에서는 main()메서드를 포함하며 출력문구를 사용하지 않는다. 
		 * 		3. Theater_Method의 멤버변수 혹은 멤버메서드를 호출하여 출력문구 및 로직을 처리한다.
		 * 
		 * Theater
		 *    main() : 메뉴를 종료를 선택하기 전까지 반복하여 보여주고 선택된 번호에 따라 기능을 수행한다.
		 * 
		 * Theater_Method
		 * 	   멤버 변수
		 * 		외부에서의 데이터의 접근을 막기 위해 다음과 같이 선언한다.
		 * 		private int[][] seats = new int[7][7];
		 * 
		 * 	   멤버 메서드
		 * 		1. printMenu() : 메뉴를 출력한다.
		 * 		2. inputCnt() : 예약할 좌석의 개수를 입력받아 반환한다.
		 * 		3. seatInfo() : 2차원배열을 이용하여 극장 좌석의 예약현황을 보여준다.
		 * 				(예약 X : 1, 예약 O : 0)
		 * 		4. reservationSeats(int cnt) : 예약할 좌석의 개수를 매개변수(parameter)로 받고
		 * 				그 횟수만큼 행과 열의 값을 입력받는다.
		 * 				a. 예약이 되어 있지 않을 경우(해당 행과 열의 값이 0일때), 
		 * 				      해당 행과 열의 값을 1로 변경하고, "예약되었습니다."라는 문구를 출력한다.
		 * 				b. 예약이 되어 있는 경우(해당 행과 열의 값이 0일때),
		 * 				   "x행x열은 예약된 좌석입니다."라는 문구를 출력하고, 다시 행과 열을 입력 받는다.
		 * */
		
		
		Theater_Method tm = new Theater_Method();
		Scanner scan = new Scanner(System.in);
		int num = 0, cnt = 0;
		
		tm.printText(3);
		while(true) {
			tm.printMenu();
			num = scan.nextInt();
			switch (num) {
				case 1:
					tm.seatInfo();
					break;
				case 2:
					cnt = tm.inputCnt();
					tm.reservationSeats(cnt);		
					break;
				case 0:
					tm.printText(1);
					return;
				default:
					tm.printText(2);
					break;
			}
		}
		
	}

}

 

 

 

Theater_Method.class

package chapter07.class_part1;

import java.util.Scanner;

public class Theater_Method {
	
	//멤버 변수
	private int[][] seats = new int[7][7];
	Scanner scan = new Scanner(System.in);
	
	//멤버 메서드
	public void printMenu() {
		System.out.println("메뉴의 번호를 선택해 주세요.");
		System.out.println("=======================");
		System.out.println("1. 좌석 확인");
		System.out.println("2. 좌석 예약");
		System.out.println("0. 종      료");		
		System.out.println("=======================");
		System.out.print("번호를 선택하세요 : ");
	}
	
	public int inputCnt() {
		int result = 0;
		
		System.out.print("몇개의 좌석을 예약하시겠습니까? : ");				
		result = scan.nextInt();
		
		return result;
	}
	
	public void printText(int num) {
		switch (num) {
			case 1:
				System.out.println("프로그램을 종료합니다.");			
				break;
			case 2:
				System.out.println("번호를 잘못 입력하셨습니다.");			
				break;
			case 3:
				System.out.println("◆ 극장 좌석 예약 프로그램◆");			
				break;
		}
	}
	
	public void seatInfo() {
		System.out.println();
		System.out.println("※좌석 예약 정보");
		System.out.println("-----------------------");
		System.out.println("   1 2 3 4 5 6 7");
		System.out.println("-----------------------");
		for (int i = 0; i < seats.length; i++) {
			System.out.print((i+1) + "| ");
			for (int j = 0; j < seats[i].length; j++) {
				System.out.print(seats[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println();
	}
	
	public void reservationSeats(int cnt) {
		
		for (int i = 0; i < cnt; i++) {
			System.out.print("예약할 좌석의 행 : ");
			int row = scan.nextInt();
			System.out.print("예약할 좌석의 열 : ");				
			int col = scan.nextInt();
			
			if(seats[row-1][col-1] != 1) {
				seats[row-1][col-1] = 1;
				System.out.println("예약되었습니다.");
			}else {
				System.out.println(row+"행 "+col+"열은 예약된 좌석입니다.");
				i--;
			}
		}
	}
}