본문 바로가기
IT/Java

Java (2차원 배열_도서관 좌석배치 메소드)

by hjshims 2021. 5. 11.

좌석확인 메소드를 호출하여 좌석이 배정되거나 반납될 때 마다 좌석확인 출력

package p0511;

import java.util.Scanner;
//좌석확인을 메소드를 호출하여 출력 (좌석배정,반납할 때 마다 좌석확인 출력) 
public class Array2_Library_Method {
	static Scanner scan = new Scanner(System.in);
	static int[][] arr = new int[5][5];
	static int i = 0, j = 0;
	static int cnt = 0;
	
	public static void check() {
		System.out.println("\t1열\t 2열\t3열\t4열\t5열");
		for (i = 0; i < arr.length; i++) {
			System.out.printf("%d행 ", i + 1);
			for (j = 0; j < arr[i].length; j++) {
				if (arr[i][j] == 0) {
					System.out.print("\t□");
				} else {
					System.out.print("\t■");
				}
			}
			System.out.println();
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		check();	//메소드 호출
		
		while (true) {

			System.out.printf("전체 25좌석 중 %d좌석이 사용중이며 %d좌석이 비어있습니다.\n\n", cnt, 25 - cnt);
			System.out.println("메뉴\n1-좌석배정\n2-좌석반납\n3-좌석확인\n4-종료");
			System.out.print("메뉴를 선택하세요. ");
			int a = scan.nextInt();

			int row, col;
			switch (a) {
			case 1: // 좌석배정
				System.out.print("앉고 싶은 행을 입력하세요. ");
				row = scan.nextInt();
				System.out.print("앉고 싶은 열을 입력하세요. ");
				col = scan.nextInt();

				if (arr[row - 1][col - 1] == 0) {
					System.out.printf(">>[%d행] [%d열]에 배정 되었습니다.\n", row, col);
					arr[row - 1][col - 1] = 1;
					cnt++;
				} else {
					System.out.printf(">>[%d행] [%d열]은 이미 배정된 좌석입니다.\n", row, col);
				}
				check();
				break;
			case 2: // 좌석반납
				System.out.print("반납할 행을 입력하세요. ");
				row = scan.nextInt();
				System.out.print("반납할 열을 입력하세요. ");
				col = scan.nextInt();
				if(arr[row-1][col-1]==0) {
					System.out.println("*반납할 좌석이 없습니다.*");
				}

				if (arr[row - 1][col - 1] == 1) {
					System.out.printf(">>[%d행] [%d열]이 반납 되었습니다.\n\n", row, col);
					arr[row - 1][col - 1] = 0;
					cnt--;
				}
				check();
				break;
			case 3: // 좌석확인
				check();
				break;
			case 4: // 종료
				System.out.println("프로그램이 종료되었습니다.");
				System.exit(0);
				break;
			}// switch끝
		}
	}

}

 

<출력결과>