[day10]
**중요**
1. this 레퍼런스
1) 객체 자기 자신을 가르키는 레퍼런스
-> 현재 실행되고 있는 메서드가 속한 실객체에 대한 레퍼런스다.

 

Class c{
	int a = 10;
	
    void X(){
    	int a = 20;
        System.out.println(a);   //20 이출력 (지역)
        System.out.println(this.a); // 10이 출력 (전역) 자기자신을 가리킴
    }
}



2) 인스턴스 매서드나 생성자에서 사용됨.
3)this의 필요성
1#. 지역변수나 매개변수와 인스턴스 변수의 이름이 같은경우
구별하려는 목적으로 사용

2#. 메서드가 객체 자기자신의 래퍼런스를 리턴해야하는 경우로 사용
**중요**
2. this()

1) 클래스안의 생성자가 다른 생성자를 호출 할 때 사용.
2) 생성자 안에서만 사용 가능
3) 생성자 안에서 다른 생성자의 기능이 필요할 때 사용
4) 생성자가 두개 이상일 경우 사용가능 (생성자 오버로딩)
5) 다른 생성자 호출 시, 반드시 생성자의 첫번째 문장이 되어야한다.
6) 코드 재사용성을 높이는 방법.

 

class Calculator{
	int a, b;
    
    public Calculator(int a, int b)
    	this.a = a;
        this.b = b;
        
       public void sum(){
       System.out.println(this.a+this.b);
	   }
       public void avg(){
       System.out.println((this.a+this.b)/2);
	   }
}

public class CalcuDemo1{
	// 생성자를 활용하여 식을 간단히
    public static void main(String[] args){
    Cacculator c1 = new Caculator(30,20);
    c1.sum(); = 50
	c1.avg(); = 25
    
    Cacculator c2 = new Caculator(10, 20);
     c1.sum(); = 30
	 c1.avg(); = 15
     }
}
package day10;

class Circle{
	int radius;
	
	Circle(int radius ){           // 라디어스값 변경 1 - 초기화 생성
		this.radius = radius;   //this.radius -> new로 만든 객체의 radius로 바뀜
	}
	void setRadius(int radius) {   // 라디어스값 변경 2 (두개 같이 써야하는 경우가 종종있음 - 2번은 메서드로 사용가능함
		this.radius = radius;
	}
	double getArea() {
	return radius * radius * 3.14;
	}
}


public class Test82 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Circle c = new Circle(5);
		System.out.println(c.getArea());
	}
}
package day10;

class Book{
	String title;
	String author;
	
	
	Book(){
		this("무제", "작자미상");
		System.out.println("생성자 1호출");
		title = "무제";
		author = "작자미상";
	}
	
	
	Book(String title){
		this(title, "작자미상"); // 생성자 안에서 첫번째 명령이 되어야한다. 다른 생성자를 부름
		System.out.println("생성자 2호출");
		//this.title=title;
		//this.author=author;
		//--->this(title, "작자미상");으로 바꿔줄수있음
	}
	
	Book(String title, String author){
		System.out.println("생성자 3호출");
		this.title=title;
		this.author=author;
	}
	void show() {
		System.out.println(title+ " "  +author);
	}
	
}

public class Test84 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
			Book book = new Book();
			Book.show();
	}
}



3. 객체배열
1) 배열은 기본타입뿐만 아니라, 객체를 요소로 갖는 객체 배열도 만들 수 있다.
2) 객체에 대한 레퍼런스(주소)들을 하나의 데이터로 저장하는 배열
3) 배열 선언 및 생성
# 선언
클래스명 [] 변수명;
int [] arr / / Tv [] arr 
#생성
변수명 = new 클래스명[방개수];
 
#줄여서
클래스명[]변수명 = new 클래스명[방개수];   // 빈 방이 만들어짐.

#저장
변수명[0] = new 클래스명();  //값을 넣음
4) 배열의 요소 객체에 접근
변수명[인덱스].맴버변수
변수명[인덱스].맴버메서드

package day10;
class Car {
	String color = "";
	Car(String color){
		this.color=color;
	}
	String drive() {
		return color + "색 차가 지나갑니다~~ ";
	}
	
}

public class Test85 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Car[] garage = new Car[5];  // 자동차 5개 저장가능한 주차장
		garage[0] = new Car("빨간");
		String [] colors = {"빨간","노란", "검정","흰색","초록"};
		
	//	garage[0].drive(); NullPointerException 발생!!!! -> 객체생성했는지
		
	for(int i = 0; i< garage.length; i++) {
			garage[i] = new Car(colors[i]);
		}
		for(int i = 0; i< garage.length; i++) {
	System.out.println(garage[i].drive());
		}
	}
}
package day10;

import java.util.Scanner;

//Book2 클래스를 활용하여 2개짜리 Book2 타입 객체 배열을 만들고,
// 사용자로부터 책의 제목과 저자를 입력받아 배열을 완성하고 출력하세요
// 출력 예 : 어린왕자, 생텍쥐베리
class Book2{
	String title;
	String author;
	Book2(String title, String author){
		this.title = title;
		this.author = author;

	}
	
}
public class Test86 {

		public static void main(String[] args) {
			// TODO Auto-generated method stub
			Book2[] books = new Book2[2];  //  배열 두칸만들기
			Scanner sc = new Scanner(System.in);
				
			
		for(int i = 0; i< books.length; i++) {  //배열 크기만큼 반복
				System.out.println("제목>>");
				String title = sc.nextLine();
				System.out.println("저자 >>");
				String author = sc.nextLine();
				books[i] = new Book2(title, author);
		}
		// 배열 크기만큼 반복
		for(int i = 0; i < books.length; i++) {
			System.out.println(books[i].title + " , "+ books[i].author);
		}
	}
}



4. 객체의 소멸
자바에서는 객체를 생성 (메모리를 점유)하는 new 연산자는 있지만, 
객체를 소멸(메모리 해제)하는 연산자는 없다.
대신 가비지 컬렉터가 적절한 시점에 자동으로 실행되어 메모리를 해제해준다. 

5. 가비지
더 이상 사용되지 않는 객체나 배열 메모리를 칭함.
참조하는 레퍼런스가 하나도 없는 객체나 배열을 가비지로 판단.

a= new Person("피카츄")  (a 피카츄를 가리키는중)
b= new Person("꼬부기")  (b 꼬부기를 가리키는중)

b= a; (b에게 a대입 = b 피카츄를 가리킴)  -> 꼬부기 사라짐 

6. 가비지 컬렉션 Gabage Collection
가비지를 자동적으로 처리함
인터넷 검색해봐야함 

7. 접근 지정자 modifier

1) 객체 지향 언어는 접근지정자를 두고있다.
객체를 캡슐화 하기 때문에, 객체에 다른 객체가 접근하는것을 
허용할지 말지를 지정할 필요가 있기 때문

2) 패키지 package
자바는 서로 관련있는 클래스 파일들을 패키지에 묶어서 저장하여 관리함.
패키지: 디렉토리 or 폴더 개념

3) 자바의 4가지 접근 지정자

# 클래스 접근 지정자 : 다른 클래스에서 이 클래스를 활용할 수 있는지 허용 여부 지정.
1. public 클래스
: 패키지에 상관없이 다른 어떤 클래스에서도 사용이 허용.
public class 클래스명 {....}

2. default 클래스
: 같은 패키지내의 클래스들에게만 사용이 허용됨
class 클래스명 {...}


# 맴버 접근 지정자 :  이 맴버를 활용 할 수 있는지 허용 여부 지정.

클래스 \ 맴버 접근지정자 private dafault protected public
같은 패키지 클래스 X O O O
다른 패키지 클래스 X X X O
접근 가능 영역 클래스안 동일패키지 동일패키지 
+
자식클래스
모든 클래스



1. public 맴버
: 모든 클래스에서 접근 가능 

public 타입 변수명
public 리턴타입 메서드명(){...}
2. private 맴버 
: 비공개, 같은 클래스안의 맴버들에게만 접근 허용

private 타입 변수명
private 리턴타입 메서드명(){...}

3. protected 멤버
: 보호된 공개, 같은 패키지의 모든 클래스와 다른 패키지에 있어도
자식 클래스라면 접근 허용 -> 상속유도

protected 타입 변수명
protected 리턴타입 메서드명(){...}

4. default 멤버
: 같은 패키지의 클래스들에게 접근허용

타입 변수명
리턴 타입 매서드명(){...}

package day10;
//defualt 클래스 : 같은 패키지
class Sample {
   public int a ;   // 모두 허용
   private int b;   // 같은 클래스
   int c;           // 같은 패키지
   protected int d; // 같은패키지 + 자식 클래스

}
// public 클래스 : 전체공개
public class Test87 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			Sample s = new Sample();
			s.a = 10;
			//s.b = 100; 접근 불가능
			s.c = 200;
			s.d = 300;
	}
}


4) 캡슐화 encaptulation : 자바가 지향하는 코드 스타일

변수 : private
메서드 : public

데이터를 보관하는 변수에 접근하기위해서는 
메서드를 통해 우회접근하도록하여,
데이터의 무분별한 공개를 막고, 적합한 가공과 검증을 통하여
데이터에 접근하도록 유도하는 방법.

getter / setter
(외부에서 보내주는거 / 외부에서 세팅)

get변수명 (){} : 데이터 꺼내기
set변수명 (){} : 데이터 대입
* 변수명 첫글자 대문자로 !!

private String name;
public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

package day10;
 // 캡슐화로 클래스 만들어보자
class Person{
	//String name = '';
	//int age = 0;
	private String name;
	private int age;
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		if(name == null) {
			System.out.println("null 은 저장할 수 없습니다");
		}else {
			
		
		 this.name = name;
		}
	}
	
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		// 검증처리, 유효성 검사
		if(age>0 && age<150) {
			
			this.age = age;   //대입
		}else {
			System.out.println("이상한 나이");
		}
	}
	
}
public class Test88 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Person p = new Person();
		//p.name = "피카츄"
		p.setAge(160);
		
		//System.out.println(p.name);
		System.out.println(p.getAge());
		
		p.setName("d");
		
		//System.out.println(p.name);
		System.out.println(p.getName());
		
	}
}

 

 

 

package day10;
// 같은 이름의 변수 우선순위 : 지역 > 인스턴스 > 클래스
public class Test83 {
	int x = 10;
		void add (int x) {
			// 인스턴스보다 지역변수가 우선순위가 높으므로, x는 모두 매게변수만 가르키게됨.
			//x = x;
			this.x = x;
		}
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
	}
}
package day10;
class Car {
	String color = "";
	Car(String color){
		this.color=color;
	}
	String drive() {
		return color + "색 차가 지나갑니다~~ ";
	}
	
}

public class Test85 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Car[] garage = new Car[5];  // 자동차 5개 저장가능한 주차장
		garage[0] = new Car("빨간");
		String [] colors = {"빨간","노란", "검정","흰색","초록"};
		
	//	garage[0].drive(); NullPointerException 발생!!!! -> 객체생성했는지
		
	for(int i = 0; i< garage.length; i++) {
			garage[i] = new Car(colors[i]);
		}
		for(int i = 0; i< garage.length; i++) {
	System.out.println(garage[i].drive());
		}
	}
}

 

 

 

 

 

 

 

 

 

 

 

package day10;
/*
	main() 메서드를 실행하였을때 예시와 같이 출력되도록 Tv 클래스를 작성하세요. 
	콘솔 출력예 > LG에서 만든 2022년형 32인치 TV
*/
class Tv{
	   private String brand;
	   private int year;
	   private int inch;


Tv(String brand, int year, int inch){
		this.brand = brand;
		this.year = year;
		this.inch = inch;
	 }
public String getBrand() {
    return brand;
 }
 
 public void setBrand(String brand) {
    this.brand = brand;
 }
 public int getYear() {
    return year;
 }
 public void setYear(int year) {
    this.year = year;
 }
 public int getInch() {
    return inch;
 }
 public void setInch(int inch) {
    this.inch = inch;
 }
		
	
	 public void show(){
		System.out.println(this.brand + "에서 만든" + this.year + 
				"년형" + this.inch +"인치 Tv");
	 }
}

public class Test89 {
	public static void main(String[] args) {
		// main은 작성완료, 주석해제하고 실행하면 지문에 나온 콘솔출력예처럼 보이게 작업. 
		Tv myTv = new Tv("LG", 2022, 32); 
		myTv.show(); 
	}
}

 

 

package day10;

import java.util.Scanner;

/*
 	Grade 클래스를 완성하세요. 
 	3과목의 점수를 입력받아 Grade 객체를 생성하고 성적 평균을 출력하는 
 	main() 과 실행예씨는 아래와 같다. 
 	콘솔 출력예)
 		수학, 과학, 영어점수를 입력하세요. 
 		수학 >> 90
 		과학 >> 88
 		영어 >> 96
 		평균은 91
*/
class Grade {
	private int math;
	private int sci;
	private int eng;
	double avg;
	Grade(int math, int sci, int eng){
		this.math = math;
		this.sci = sci;
		this.eng = eng;
	}
	
	public int getMath() {return math;}
	public void setMath(int math) {this.math=math;}
	public int getsci() {return sci;}
	public void setSci(int sci) {this.sci=sci;}
	public int getEng() {return eng;}
	public void setEng(int eng) {this.eng=eng;}
	
	
	
	double getAvg() {
		return (math + sci + eng)/3;
	}
}

public class Test90 {
	public static void main(String[] args) {
		//main 완성 
		Scanner sc = new Scanner(System.in);
		System.out.println("수학, 과학, 영어점수를 입력하세요.");
		System.out.print("수학>>");
		int math = Integer.parseInt(sc.nextLine());
		System.out.print("과학>>");
		int sci = Integer.parseInt(sc.nextLine());
		System.out.print("영어>>");
		int eng = Integer.parseInt(sc.nextLine());
		
		Grade me = new Grade(math, sci, eng);
		System.out.println("평균은 " + me.getAvg());
		
		sc.close();
	}
}

 

package day10;

/*
	노래 한곡을 나타내는 Song 클래스를 작성하세요. Song은 아래와 같은 변수로 구성된다. 
		- 노래 제목을 나타내는 title 
		- 가수를 나타내는 artist
		- 노래가 발표된 연도를 나타내는 year
		- 국적을 나타내는 country 
	또한, Song클래스에 다음 생성자와 메서드를 작성하세요. 
		- 생성자 2개 : 기본생성자, 매개변수로 모든 변수를 초기화해주는 생성자 
		- 노래 정보를 출력하는  show() 메서드 
		- main() 메서드에서는 2017년, 한국국적의 Collective Arts가 부를 Alone이라는 
		 	Song 객체를 생성하고, show() 를 이용하여 노래의 
			정보를 이용하여 아래와 같이 출력되도록 하세요. 
	콘솔 출력예 >> 2017년 한국국적의 Collective Arts가 부른 Alone
*/
class Song {
	String title;
	String artist;
	int year;
	String country;
	
	Song(){} //기본 생성자
	Song(String title, String artist, int year, String country){  //매게변수로 모든변수 초기화
		this.title = title;
		this.artist = artist;
		this.year = year;
		this.country = country;
	
	 }
	
	void show(){
		System.out.println( year +"년 " +country +" 국적의 " + artist + "가 부른 " + title);
	}
}
public class Test91 {
	public static void main(String[] args) {

		Song s = new Song();
		Song album= new Song("제목","아티스트 ",2022,"한국");
		s.show();
		album.show();
	}
}

 

 

package day10;
/*
	직사각형을 표현하는 Rectangle 클래스를 작성하세요. 
	- int 타입의 x, y, width, height 변수 : 사각형을 구성하는 점과 크기 정보 
		x,y는 사각형 왼쪽 위 점의 좌표를 말함. 
		0,0은 왼쪽 위, x는 오른쪽으로 늘어나고 y는 밑으로 늘어난다. 
	- x, y, width, height 값을 매개변수로 받아 필드를 초기화 하는 생성자 
	- int squareArea()	: 사각형의 너비를 리턴 
	- void show()		: 사각형의 좌표와 가로세로 출력 
	- boolean contains(Rectangle r) : 매개변수로 받은 r이 현 사각형 안에 있으면 true리턴 
	- 콘솔 출력 결과 :
		(2,2)에서 크기가 8x7인 사각형 
		b의 면적은 36
		c는 a를 포함합니다. 
*/
class Rectangle{


	int x,y,width,height ;

	Rectangle(int x, int y, int width, int height){
	this.x=x;
	this.y=y;
	this.width=width;
	this.height=height;
	}


	int squareArea() {
	return (width)*(height);
}
	void show() {
		System.out.println("("+x+","+y+")+에서 크기가 " + width + "*"+height + "인 사각형");
	}

	boolean contains(Rectangle r) {
		if(x<r.x && y<r.y && (x+width)>(r.x+r.width)&& (y+height)>(r.y + r.height)) {
			return true;
		}
		return false;
	}
}
public class Test92 {
	public static void main(String[] args) {

		// main은 작성 완료. 주석해제해서 실행 
		
		
		Rectangle a = new Rectangle(2,2,8,7); // x. y. width. height
		Rectangle b = new Rectangle(5,5,6,6); 
		Rectangle c = new Rectangle(1,1,10,10); 
		
		a.show(); 
		System.out.println("b의 면적은 " + b.squareArea());
		if(c.contains(a)) { System.out.println("c는 a를 포함합니다."); }
		if(c.contains(b)) { System.out.println("c는 b를 포함합니다."); }

	}
}

 

 

package day10;

import java.util.Scanner;

/*
	n명이 참가하는 끝말잇기 게임을 만들어보자. 
	처음단어는 "자동차"이다. 
	몇명(n)이 참가하는지 입력받고, n명의 참가자들은 순서대로 자신의 단어를 입력하면된다. 
	끝말잇기에서 틀리면 게임오버 -> 진사람 이름 출력하고 프로그램 종료. 
	WordGameApp 클래스와 각 선수를 나타내는 Player 클래스로 구성하세요. 
	WordGameApp : 게임을 전체적으로 진행하는 run() 메서드, 
				run()에서 플레이어 수만큼 Player 객체 배열 생성 
	Player : 플레이어 이름 저장, 단어 입력받는 getWordFromUser()메서드, 
			끝말잇기 성공여부와 게임계속할지 판별하는 checkSuccess() 메서드 
	# 힌트 
		* 문자열 첫번째 문자 알아내는 방법 
			String word = "자동차"; 
			char ch = word.charAt(0); 
		* 문자열의 길이 알아내는 방법 
			word.length(); --> 3 
*/
class Player {
	// 캡슐화 
	private String name;	// 플레이어 이름 
	private String word;	// 이 플레이어가 입력한 단어 저장해놓을 변수 
	public String getName() { return name; }
	public void setName(String name) { this.name = name; }
	String getWordFromUser(Scanner sc) {
		System.out.print(name + " >> ");
		word = sc.nextLine(); 
		return word;
	}
	boolean checkSuccess(String lastWord) { // 맞았는지 체크 : 방금입력한단어, 이전단어 
		boolean check = false; 
		// lastWord 끝 글자 찾기 
		int lastIdx = lastWord.length() - 1;  // 마지막 글자의 인덱스번호 찾기
		char lastChar = lastWord.charAt(lastIdx); // 마지막글자 꺼내오기
		// 입력한 word의 첫글자 찾기 
		char firstChar = word.charAt(0);
		// 두개비교 
		if(lastChar == firstChar) { // 두개가 같으면 
			check = true; // 결과 true로 변경
		}
		return check; // 결과 담고있는 변수의 값 리턴 
	}
}
class WordGameApp {
	Player[] p = null; 	// 플레이어들을 객체로 생성해서 저장시켜놓을 배열변수
	Scanner sc; 
	
	WordGameApp() {
		sc = new Scanner(System.in);
	}
	
	// 참가인원 세팅 
	void setPlayers() {
		System.out.print("게임에 참가하는 인원 >> ");
		int num = Integer.parseInt(sc.nextLine()); 
		p = new Player[num];	// 참가인원수 만큼 방크기 만들기 (빈방)
		for(int i = 0; i < p.length; i++) { // 방크기 만큼 반복 
			// Player 객체생성해, 
			p[i] = new Player(); 
			// 참가자 이름 입력받아, 해당 배열안 객체에 바로 이름 저장
			System.out.print("이름 >> ");
			p[i].setName(sc.nextLine()); 
	         //p[i].setName(name);
			//String name = sc.nextLine(); 
		}
	}
	// 게임을 전체적으로 진행시킬 메서드 
	void run() {
		System.out.println("끝말잇기 게임시작!!!");
		setPlayers();
		// 게임 진행 
		String lastWord = "자동차";
		System.out.println("시작 단어는 " + lastWord + "입니다.");
		int idx = 0; // while 안에서 인덱스번호 처럼 사용할 변수 
		while(true) {
			// 단어 입력받고 
			String newWord = p[idx].getWordFromUser(sc);
			// 맞았는지 검사 -> 맞으면 계속 돌고, 틀리면 누가 졌는지 출력하고while 종료! 
			boolean result = p[idx].checkSuccess(lastWord);
			if(!result) {
				System.out.println("게임오버!!" + p[idx].getName() + "님이 졌습니다.");
				sc.close(); // 더이상 입력받을거 없을때 닫아주기 
				break;
			}
			idx++; 
			idx %= p.length; 
			// 다음 회차를 위해 lastWord를 방금 입력받은 단어로 변경
			lastWord = newWord; 
		}
	}
}
public class Test933 {
	public static void main(String[] args) {
		// main 작성 완료!! 
		WordGameApp game = new WordGameApp(); 
		game.run(); 
		
	}
}

 

package day10;

import java.util.Scanner;

/*
	하루 할일을 표현하는 클래스 Day는 다음과 같다. (그대로 사용하기) 
	한달의 할일을 표현하는 MonthSchedule 클래스를 작성하세요. 
	MonthSchedule 클래스에는 Day 객체 배열과 적절한 변수, 메서드를 작성하고
	실행 예시처럼 입력,보기,끝내기 등의 3개의 기능을 작성하세요. 
	콘솔 실행예시 : 
		이번달 스케쥴 관리 프로그램. 
		할일(입력:1, 보기:2, 끝내기:3) >>   1  (사용자 입력) 
		날짜(1 ~ 31)?   1 
		할일?   자바공부 
		
		할일(입력:1, 보기:2, 끝내기:3) >>   2 
		날짜(1 ~ 31)?   1 
		1일의 할 일은 자바공부입니다.
		
		할일(입력:1, 보기:2, 끝내기:3) >>   3 
		프로그램 종료 
*/
class Day {
	private String work; 
	public void setWork(String work) { this.work = work; }
	public String getWork() { return work; }
	public void show() {
		if(work == null) { System.out.println("없습니다."); }
		else {System.out.println(work + "입니다.");}
	}
}
class MonthSchedule {
	private Day [] days;
	private Scanner sc;
	private int dayNum; // 다른 메서드에서 필요하면 사용하기 위해 인스턴스로 만듬
	 MonthSchedule(int dayNum){
		 days = new Day[dayNum]; // 방크기만들기 (빈방)
		 for(int i=0; i<days.length; i++) {// 방마다 day 객체 생성해 채우기
			 days[i] = new Day();
		 }
		 sc = new Scanner(System.in);
	 } 
	 void intput() {// 입력
		 System.out.println("날짜(1~  "+ dayNum + ")?");
		 int day = Integer.parseInt(sc.nextLine());
		 day--; // 인덱스 번호로 변경
		 if(day<0 || day>dayNum) {
			 System.out.println("날짜를 잘못 입력하셨습니다");
			 //input();
			 return;
		 }
		 System.out.println(" 할일 ? ");
		 String work = sc.nextLine();
		 days[day].setWork(work); //달력해당 날짜에 할일 저장
	 }
	 void show() {// 할일보기
		 System.out.println("날짜(1~  "+ dayNum + ")?");
		 int day = Integer.parseInt(sc.nextLine());
		 day--; // 인덱스 번호로 변경
		 if(day<0 || day>dayNum) {
			 System.out.println("날짜를 잘못 입력하셨습니다");
			 //input();
			 return;
		 }
		 System.out.println(day +1 +"일의 할 일은 :");
		 days[day].show();
	 }
	 void finish() {// 끝내기
		 
	 }
	 // 달력 프로그램 전체 진행시키는 메서드
	 void run() {
		 System.out.println("이번달 스케쥴 관리 프로그램.");
		 
		 while (true) {
			 System.out.println("할일(입력:1, 보기:2, 끝내기:3) >> ");
			 int menu = Integer.parseInt(sc.nextLine());
			 switch(menu) {
			 case 1: intput(); break;
			 case 2: show(); break;
			 case 3: finish(); return; // run()메서드 종료 !!
			 default : System.out.println("잘못입력했습니다 다시하세요");
			 }
		 }
		 
	 }
}
public class Test94 {
	public static void main(String[] args) {

		// main은 작성 완료 
		//MonthSchedule may = new MonthSchedule(31); // 5월달 스케쥴 생성 
		//may.run();  0
		
	}
}

 

package day10;

import java.util.Scanner;

/*
	콘서트 예약 프로그램 
	- 공연은 하루만 예약 
	- 좌석은 S석, A석, B석으로 나뉘며, 각 10개의 좌석이 있다. 
	- 예약 시스템의 메뉴는 "예약", "조회", "취소", "끝내기" 가 있다. 
	- 예약은 한자리만 가능하고, 좌석타입, 예약자이름, 좌석번호를 입력받아 예약한다. 
	- 조회는 모든 좌석을 출력한다. 
	- 취소는 예약자의 이름을 입력받아 취소한다. 
	- 없는이름, 없는메뉴번호, 없는좌석번호 등 예외가 발생할것들을 미리 처리
		-> 오류 메세지 출력하고 사용자가 다시 시도하도록 한다. 
	실행 예시 : 
		자바콘서트홀 예약시스템입니다. 
		예약:1, 조회:2, 취소:3, 끝내기4 >>   1 
		좌석구분 S(1), A(2), B(3) >>  1 
		S >> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
		이름 >>   피카츄 
		번호 >>   1 
		<<예약 완료>>
		
		예약:1, 조회:2, 취소:3, 끝내기4 >>   1 
		좌석구분 S(1), A(2), B(3) >>  2 
		A >> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
		이름 >>   꼬북이 
		번호 >>   5 
		<<예약 완료>>
		
		예약:1, 조회:2, 취소:3, 끝내기4 >>   2 
		S >> 피카츄 ___ ___ ___ ___ ___ ___ ___ ___ ___
		A >> ___ ___ ___ ___ 꼬북이 ___ ___ ___ ___ ___
		B >> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
		<<조회 완료>>
		
		예약:1, 조회:2, 취소:3, 끝내기4 >>   3 
		좌석구분 S(1), A(2), B(3) >>  2 
		A >> ___ ___ ___ ___ 꼬북이 ___ ___ ___ ___ ___
		이름 >>  꼬북이 
		<<취소 완료>>
		
		예약:1, 조회:2, 취소:3, 끝내기4 >>   2 
		S >> 피카츄 ___ ___ ___ ___ ___ ___ ___ ___ ___
		A >> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
		B >> ___ ___ ___ ___ ___ ___ ___ ___ ___ ___
		<<조회 완료>>
		
		예약:1, 조회:2, 취소:3, 끝내기4 >>   4
		<<프로그램 종료>>
*/
class Seat { // 좌석 한개 정보 담을 클래스 
	private String name = "___"; 
	public void setName(String name) { this.name = name; }
	public String getName() { return name; }
}

class Booking { // 예약 프로그램 
	private Scanner sc; 
	private Seat[] seatS = new Seat[10]; 
	private Seat[] seatA = new Seat[10];
	private Seat[] seatB = new Seat[10]; 
	
	Booking() {
		sc = new Scanner(System.in); // Scanner 객체생성해서 사용가능하게 준비 세팅
		for(int i = 0; i < seatS.length; i++) {
			seatS[i] = new Seat(); 
		}
		for(int i = 0; i < seatA.length; i++) {
			seatA[i] = new Seat(); 
		}
		for(int i = 0; i < seatB.length; i++) {
			seatB[i] = new Seat(); 
		}
	}
	
	void showSeats(int sel) {
		if(sel == 1) {
			System.out.print("S >> ");
			for(int i = 0; i < seatS.length; i++) { 
				System.out.print(seatS[i].getName() + "  ");
			}
			System.out.println();
		}else if(sel == 2) {
			System.out.print("A >> ");
			for(int i = 0; i < seatA.length; i++) { 
				System.out.print(seatA[i].getName() + "  ");
			}
			System.out.println();
		}else if(sel == 3) {
			System.out.print("B >> ");
			for(int i = 0; i < seatB.length; i++) { 
				System.out.print(seatB[i].getName() + "  ");
			}
			System.out.println();
		}
	}
	void book() {
		System.out.print("좌석구분 S(1), A(2), B(3) >> ");
		int sel = Integer.parseInt(sc.nextLine());
		showSeats(sel); // 해당 좌석 출력해라 
		System.out.print("이름 >> ");
		String name = sc.nextLine(); 
		System.out.print("번호 >> ");
		int seatNum = Integer.parseInt(sc.nextLine());
		// 좌석 구역 선택한것에 따라 맞는 배열에 저장 
		if(sel == 1) seatS[seatNum-1].setName(name);
		else if(sel == 2) seatA[seatNum-1].setName(name);
		else if(sel == 3) seatB[seatNum-1].setName(name);
		System.out.println("<<예약 완료>>");
	}
	void search() {
		showSeats(1);
		showSeats(2);
		showSeats(3);
		System.out.println("<<조회 완료>>");
	}
	/*
		좌석구분 S(1), A(2), B(3) >>  2 
		A >> ___ ___ ___ ___ 꼬북이 ___ ___ ___ ___ ___
		이름 >>  꼬북이 
		<<취소 완료>>
	 */
	void cancel() {
		System.out.print("좌석구분 S(1), A(2), B(3) >> ");
		int sel = Integer.parseInt(sc.nextLine());
		showSeats(sel); // 해당 좌석 출력해라 
		System.out.print("이름 >> ");
		String name = sc.nextLine(); 
		if(sel == 1) {
			for(int i = 0; i < seatS.length; i++) {
				if(seatS[i].getName().equals(name)) {
					seatS[i].setName("___");
				}
			}
		}else if(sel == 2) {
			for(int i = 0; i < seatA.length; i++) {
				if(seatA[i].getName().equals(name)) {
					seatA[i].setName("___");
				}
			}
		}else if(sel == 3) {
			for(int i = 0; i < seatB.length; i++) {
				if(seatB[i].getName().equals(name)) {
					seatB[i].setName("___");
				}
			}
		}
	}

	void run() {
		System.out.println("자바콘서트홀 예약시스템입니다.");
		while(true) {
			// 반복해서 메뉴 번호 입력받고,
			System.out.print("예약:1, 조회:2, 취소:3, 끝내기4 >> ");
			int menu = Integer.parseInt(sc.nextLine());
			if(menu == 1) { book(); }
			else if(menu == 2) { search(); }
			else if(menu == 3) { cancel(); }
			else if(menu == 4) {
				System.out.println("예약 프로그램 종료!!");
				sc.close();
				break;
			}
			else {
				System.out.println("메뉴 선택 오류!! 다시 입력하세요...");
			}
			// 번호에 해당하는 처리 메서드 호출 
		}// while
	}// run
}// Booking

public class Test95 {
	public static void main(String[] args) {

		Booking book = new Booking(); 
		book.run();
		
	}
}

+ Recent posts