Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Archives
Today
Total
관리 메뉴

코딩로그

[명품 JAVA Programming] 제4장 클래스와 객체 - 실습문제 본문

YJ/JAVA

[명품 JAVA Programming] 제4장 클래스와 객체 - 실습문제

Team DAON 2020. 12. 30. 03:06

[1번]

자바 클래스를 작성하는 연습을 해보자. 다음 main() 메소드를 실행하였을 때 예시와 같이 출력되도록 TV 클래스를 작성하라.

public static void main(String[] args){
	TV myTV = new TV("LG", 2017, 32);
	myTV.show();
}
LG에서 만든 2017년형 32인치 TV
import java.util.*;


public class TV {//TV 클래스
	String company;//회사명 저장 변수
	int year;//연도 저장 변수
	int inchi;//인치 저장 변수
	
	public TV(String c, int y, int i) {//초기화를 위한 생성자
		company = c;//company 초기화
		year = y;//year 초기화
		inchi = i;//inchi 초기화
	}
	public void show() {//문장 출력을 위한 함수 선언
		System.out.println(company+"에서 만든 "+year+"년형 "+inchi+"인치 TV");
	}
	
	public static void main(String[] args) {
	    TV myTV = new TV("LG", 2017, 32);//객체 생성, c는 LG, y는 2017, i는 32로 전달
		myTV.show();//문장 출력을 위한 함수 호출
	}
}

실행 결과


[2번]

Grade 클래스를 작성해보자. 3 과목의 점수를 입력받아 Grade 객체를 생성하고 성적 평균을 출력하는 main()과 실행 에시는 다음과 같다.

public static void main(String[] args) {
	    Scanner scanner = new Scanner(System.in);
	    
	    System.out.println("수학, 과학, 영어 순으로 3개의 점수 입력>>");
	    int math = scanner.nextInt();
	    int science = scanner.nextInt();
	    int english = scanner.nextInt();
	    
	    Grade me = new Grade(math, science, english);
	    System.out.println("평균은 "+me.average());
	    
	    scanner.close();
	}
실행 결과
수학, 과학, 영어 순으로 3개의 점수 입력>>90 88 96
평균은 91

Hint!
Grade 클래스에 int 타입의 math, science, english 필드를 private으로 선언하고,
생성자와 세 과목의 평균을 리턴하는 average() 메소드를 작성한다.
import java.util.*;


public class Grade {//Grade 클래스
	private int m;//수학 점수
	private int s;//과학 점수
	private int e;//영어 점수
	
	public Grade(int math, int science, int english) {
		m = math;//수학 점수 초기화
		s = science;//과학 점수 초기화
		e = english;//영어 점수 초기화
	}
	
	public int average() {
		return (m+s+e)/3;//평균 계산 후 반환
	}
	
	public static void main(String[] args) {
	    Scanner scanner = new Scanner(System.in);
	    
	    System.out.print("수학, 과학, 영어 순으로 3개의 점수 입력>>");
	    int math = scanner.nextInt();
	    int science = scanner.nextInt();
	    int english = scanner.nextInt();
	    
	    Grade me = new Grade(math, science, english);//객체 생성
	    System.out.println("평균은 "+me.average());//평균 출력
	    
	    scanner.close();
	}
}

실행 결과


[3번]

노래 한 곡을 나타내는 Song 클래스를 작성하라. Song은 다음 필드로 구성된다.

  • 노래 제목을 나타내는 title
  • 가수를 나타내는 artist
  • 노래가 발표된 연도를 나타내는 year
  • 국적을 나타내는 country

또한 Song 클래스에 다음 생성자와 메소드를 작성하라

  • 생성자 2개: 기본 생성자와 매개변수로 모든 필드를 초기화하는 생성자
  • 노래 정보를 출력하는 show() 메소드
  • main() 메소드에서는 1978년, 스웨덴 국적의 ABBA가 부른 "Dancing Queen"을 Song 객체로 생성하고 show()를 이용하여 노래의 정보를 다음과 같이 출력하라.
1978년 스웨덴국적의 ABBA가 부른 Dancing Queen
import java.util.*;


public class Song {//Song 클래스
	private String title;//제목
	private String artist;//가수
	private int year;//발매 연도
	private String country;//국적
	
	public Song() {//기본 생성자, 전달받은 값이 없는 경우 실행
		title = "제목";
		artist = "가수";
		year = 0000;
		country = "국적";
	}
	
	public Song(String t, String a, int y, String c) {//매개변수로 모든 필드를 초기화하는 생성자
		title = t;//제목 초기화
		artist = a;//가수 초기화
		year = y;//연도 초기화
		country = c;//국적 초기화
	}
	
	public void show() {//문장 출력을 위한 함수
		System.out.print(year+"년 "+country+"국적의 "+artist+"가 부른 "+title);
	}
	
	public static void main(String[] args) {
	    Song song = new Song("Dancing Queen", "ABBA", 1978, "스웨덴");//객체 생성
	    song.show();//문장 출력을 위한 show 함수 호출
	}
}

실행 결과


[4번]

다음 멤버를 가지고 직사각형을 표현하는 Rectangle 클래스를 작성하라.

  • int 타입의 x, y, width, height 필드: 사각형을 구성하는 점과 크기 정보
  • x, y, width, height 값을 매개변수로 받아 필드를 초기화하는 생성자
  • int square(): 사각형의 넓이 리턴
  • void show(): 사각형의 좌표와 넓이를 화면에 출력
  • boolean contains(Rectangle r): 매개변수로 받는 r이 현 사각형 안에 있으면 true 리턴
  • main() 메소드의 코드와 실행 결과는 다음과 같다.
public static void main(String[] args) {
	    Scanner scanner = new Scanner(System.in);
	   	
	    Rectangle r = new Rectangle(2, 2, 8, 7);
	    Rectangle s = new Rectangle(5, 5, 6, 6);
	    Rectangle t = new Rectangle(1, 1, 10, 10);
	    
	    r.show();
	    System.out.println("s의 면적은 "+s.square());
	    if(t.contains(r)) System.out.println("t는 r을 포함합니다.");
	    if(t.contains(s)) System.out.println("t는 s를 포함합니다.");
	    
	    scanner.close();
	}
    
실행 결과
(2,2)에서 크기가 8x7인 사각형//r.show()가 출력한 내용
s의 면적은 36
t는 r을 포함합니다.
import java.util.*;


public class Rectangle {//Rectangle 클래스
	private int x;//x좌표
	private int y;//y좌표
	private int width;//넓이
	private int height;//높이
	
	public Rectangle(int in_x, int in_y, int in_width, int in_height) {//생성자
		x = in_x;
		y = in_y;
		width = in_width;
		height = in_height;
	}
	
	public void show() {//문장 출력을 위한 함수 선언
		System.out.println("("+x+","+y+")에서 크기가 "+width+"x"+height+"인 사각형");
	}
	
	public int square() {//사각형의 넓이 반환 함수 선언
		return width*height;//가로*세로
	}
	public boolean contains(Rectangle a) {//포함 여부 반환 함수
		if(x < a.x && y < a.y) {//x, y가 비교할 x, y보다 작아야 하며
	         if((width+x) > (a.x+a.width) && (height+y) > (a.y+a.height)) {
	        	 //길이와 높이를 더한 다른 점의 위치가 비교할 것보다 커야 한다.
	        	 return true;
			}
	         else {
	        	 return false;
	         }
		}
		else {
			return false;
		}
	}
	
	public static void main(String[] args) {
	    Rectangle r = new Rectangle(2, 2, 8, 7);//객체 생성
	    Rectangle s = new Rectangle(5, 5, 6, 6);//객체 생성
	    Rectangle t = new Rectangle(1, 1, 10, 10);//객체 생성
	    
	    r.show();//문장을 출력하는 함수 호출
	    System.out.println("s의 면적은 "+s.square());//사각형의 넓이를 구하는 함수 호출
	    if(t.contains(r)) System.out.println("t는 r을 포함합니다.");//r을 매개변수로, t에 포함 여부를 판단하는 함수 호출
	    if(t.contains(s)) System.out.println("t는 s를 포함합니다.");//s를 매개변수로, t에 포함 여부를 판단하는 함수 호출
	}
}

실행 결과


[5번]

다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라.

import java.util.*;


public class Circle {
	private double x, y;
	private int radius;
	public Circle(double x, double y, int radius) {
		_______________________________________;
	}
	public void show() {
		_______________________________________
	}
}

public CircleManager{
	public static void main(String[] args) {
		Scanner scanner = __________________;
		Circle c [] = __________________;
		for(int i = 0; i< __________________; i++) {
			System.out.print("x, y, radius>>");
			_______________________________________;
			_______________________________________;
			_______________________________________;
			c[i] =  __________________;
		}
		for(int i = 0; i<c.length; i++)  __________________;
		scanner.close();
	}
}

다음 실행 결과와 같이 3개의 Circle 객체 배열을 만들고 x, y, radius 값을 읽어 3개의 Circle 객체를 만들고 show()를 이용하여 이들을 모두 출력한다.

x, y, radius>>3.0 3.0 5
x, y, radius>>2.5 2.7 6
x, y, radius>>5.0 2.0 4
(3.0,3.0)5
(2.5,2.7)6
(5.0,2.0)4

 

import java.util.*;


class Circle {//Circle 클래스
	private double x, y;
	private int radius;
	public Circle(double x, double y, int radius) {//초기화를 위한 생성자
		this.x = x;//x, y, radius 초기화
		this.y = y;
		this.radius = radius;
	}
	public void show() {//문장 출력을 위한 함수 선언
		System.out.println("("+this.x+","+this.y+")"+this.radius);
	}
}

public class CircleManager {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		Circle c [] = new Circle[3];//3개의 Circle 배열 선언
		for(int i = 0; i<c.length; i++) {//배열 개수만큼 반복
			System.out.print("x, y, radius>>");
			double x = scanner.nextDouble();//x값 읽기
			double y = scanner.nextDouble();//y값 읽기
			int radius = scanner.nextInt();//반지름 읽기
			c[i] = new Circle(x, y, radius);//Circle 객체 생성
		}
		for(int i = 0; i<c.length; i++) c[i].show();//Circle 객체 수만큼 반복, 문장 출력
		scanner.close();
		
	}
}

실행 결과


[6번]

앞의 5번 문제는 정답이 공개되어 있다. 이 정답을 참고하여 Circle 클래스와 CircleManager 클래스를 수정하여 다음 실행 결과처럼 되게 하라

x, y, radius>>3.0 3.0 5
x, y, radius>>2.5 2.7 6
x, y, radius>>5.0 2.0 4
가장 면적이 큰 원은 (2.5, 2.7)6
import java.util.*;


class Circle {//Circle 클래스
	private double x, y;//x, y, radius 선언
	private int radius;
	public Circle(double x, double y, int radius) {//초기화를 위한 생성자
		this.x = x;//x, y, radius 초기화
		this.y = y;
		this.radius = radius;
	}
	public void show() {//문장 출력을 위한 함수 선언
		System.out.println("가장 면적이 큰 원은 ("+this.x+","+this.y+")"+this.radius);
	}
}

public class CircleManager {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		Circle c [] = new Circle[3];//3개의 Circle 배열 선언
		int count = -1; //가장 큰 면적을 가진 객체를 구별하기 위한 변수
		double max = 0;// 가장 큰 면적을 구별하기 위해 면적을 저장할 변수
		
		for(int i = 0; i<c.length; i++) {//배열 개수만큼 반복
			System.out.print("x, y, radius>>");
			double x = scanner.nextDouble();//x값 읽기
			double y = scanner.nextDouble();//y값 읽기
			int radius = scanner.nextInt();//반지름 읽기
			if(max < Math.PI*radius*radius) {//원의 면적이 max보다 큰 경우
				max = Math.PI*radius*radius;//max에 원의 면적 저장
				count = i;//가장 큰 원이 i번째임을 기록하기 위해 count에 저장
			}
			c[i] = new Circle(x, y, radius);//Circle 객체 생성
		}
		c[count].show();//면적이 가장 큰 원의 문장 출력 함수 호출
		scanner.close();
	}
}

실행 결과


[7번]

하루의 할 일을 표현하는 클래스 Day는 다음과 같다. 한 달의 할 일을 표현하는 MonthSchedule 클래스를 작성하라.

class Day {
	private String work;//하루의 할 일을 나타내는 문자열
	public void set(String work) { this.work = work; }
	public String get() { return work; }
	public void show() {
		if(work == null) System.out.println("없습니다.");
		else System.out.println(work+"입니다.");
	}
}

MonthSchedule 클래스에는 Day 객체 배열과 적절한 필드, 메소드를 작성하고 실행 예시처럼 입력, 보기, 끝내기 등의 3개의 기능을 작성하라.

Hint!
MonthSchedule에는 생성자 input(), view(), finish(), run() 메소드를 만들고
main()에서 다음과 같이 호출하여 실행하고 run()에서 메뉴를 출력하고 처리한다.

MonthSchedule april = new MonthSchedul(30);
april.run();
import java.util.*;


class Day {//Day 클래스
	private String work;//하루의 할 일을 나타내는 문자열
	public void set(String work) { this.work = work; }//할 일 초기화
	public String get() { return work; }//할 일 리턴
	public void show() {//문장 출력, 할 일 유무에 따라 다른 값 저장
		if(work == null) System.out.println("없습니다.");
		else System.out.println(work+"입니다.");
	}
}

public class MonthSchedule {
	Scanner scanner = new Scanner(System.in);
	private String schedule;//일정 저장 변수
	private int day;//날짜 저장 변수
	private Day [] d;//Day 배열
	
	public MonthSchedule(int day) {//생성자
		this.day = day;//날짜 초기화
		this.d = new Day[day];//배열 선언
		for(int i = 0; i<d.length; i++) {
			d[i] = new Day();//d의 개수만큼 반복, 날짜 별 일정 만들기
		}
	}
	public void input() {//일정 입력 함수
		System.out.print("날짜(1~30)?");
		day = scanner.nextInt();//날짜 저장
		System.out.print("할일(빈칸없이입력)?");
		schedule = scanner.next();//할 일 저장
		day--;//배열에 저장하기 위해 하나 작은 값으로 바꾸기
		d[day].set(schedule);//일정 저장
	}
	public void view() {//일정 보기 함수
		System.out.print("날짜(1~30)?");
		day = scanner.nextInt();//날짜 저장
		System.out.print(day+"일의 할 일은 ");
		day--;//저장된 값을 불러오기 위해 배열에 맞춰 하나 작은 값으로 바꾸기
		d[day].show();//일정 출력
	}
	public void finish() {//프로그램 종료용 함수
		System.out.println("프로그램을 종료합니다.");
	}
	public void run() {//프로그램 실행 함수
		System.out.println("이번달 스케줄 관리 프로그램.");
		int choice = 0;//선택값을 저장할 변수
		while(true) {//break 전까지 무한 반복
			System.out.print("할일(입력:1, 보기:2, 끝내기:3) >>");
			choice = scanner.nextInt();
			if(choice == 1) {//입력을 선택한 경우
				input();//함수 실행
			}
			else if(choice == 2) {//보기를 선택한 경우
				view();//함수 실행
			}
			else if(choice == 3) {//끝내기를 선택한 경우
				finish();//함수 실행
				break;//while문에서 벗어나기
			}
			System.out.println();
		}	
	}
	public static void main(String[] args) {
		MonthSchedule april = new MonthSchedule(30);//객체 생성
		april.run();//프로그램 실행용 함수
	}
}

 

실행 결과


[8번]

이름(name), 전화번호(tel) 필드와 생성자 등을 가진 Phone 클래스를 작성하고, 실행 예시와 같이 작동하는 PhoneBook 클래스를 작성하라.

 

인원수>>3
이름과 전화번호(이름과 번호는 빈 칸 없이 입력)>>황기태 777-7777
이름과 전화번호(이름과 번호는 빈 칸 없이 입력)>>나명품 999-9999
이름과 전화번호(이름과 번호는 빈 칸 없이 입력)>>최자바 333-1234
저장되었습니다...
검색할 이름>>황기순
황기순이 없습니다.
검색할 이름>>최자바
최자바의 번호는 333-1234 입니다.
검색할 이름>>그만

Hint!
PhoneBook 클래스에서 저장할 사람의 수를 입력받고, Phone 객체 배열을 생성한다.
한 사람의 정보는 하나의 Phone 객체에 저장한다. 7번 정답을 참고하길 바란다.
문자열 a와 b가 같은지 비교할 때 a.equals(b)가 참인지로 판단한다.
import java.util.*;


class Phone {//Phone 클래스
	private String name;//이름 저장 변수
	private String tel;//전화번호 저장 변수
	
	public Phone(String name, String tel) {//이름, 전화번호 초기화용 생성자
		this.name = name;
		this.tel = tel;
	}
	public String get_name() {//이름을 반환하는 함수
		return this.name;
	}
	public void show() {//문장 출력용 함수
		if(tel != null) {//전화번호가 존재하는 경우 문장 출력
			System.out.println(this.name+"의 번호는 "+this.tel+" 입니다.");
		}
	}
}

public class PhoneBook {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.print("인원수>>");
		int num = scanner.nextInt();//인원 수 저장
		Phone [] p = new Phone[num];//인원 수만큼 객체 생성
		for(int i = 0; i<num; i++) {//인원 수만큼 반복
			System.out.print("이름과 전화번호(이름과 번호는 빈 칸 없이 입력)>>");
			String name = scanner.next();//이름 저장
			String tel = scanner.next();//전화번호 저장
			p[i] = new Phone(name, tel);//객체 초기화
		}
		System.out.println("저장되었습니다...");
		while(true) {//break문을 만나기 전까지 무한 반복
			System.out.print("검색할 이름>>");
			String search = scanner.next();//검색할 이름 저장
			if(search.equals("그만")) {//그만을 입력한 경우
				break;//while문 벗어나기
			}
			else {//그만이 아닌 경우
				for(int i = 0; i<p.length; i++) {//객체 수만큼 반복
					if(p[i].get_name().equals(search)) {//검색할 이름과 저장된 이름이 같은 경우
						p[i].show();//문장 출력을 위한 함수 호출
					}
					else if(i==p.length-1) {//검색할 이름과 저장된 이름이 다르고 저장된 모든 객체에 대해 검색한 경우
						System.out.println(search+"이 없습니다.");//문장 출력
					}
				}
			}
		}
	}
}

실행 결과


[9번]

다음 2개의 static 가진 ArrayUtil 클래스를 만들어보자. 다음 코드의 실행 결과를 참고하여 concat()와 print()를 작성하여 ArrayUtil() 클래스를 완성하라.

import java.util.*;


class ArrayUtil {
	public static int [] concat(int[] a, int[] b) {
		/* 배열 a와 b를 연결한 새로운 배열 리턴 */
	}
	public static void print(int[] a) {/* 배열 a 출력 */}
}

public class StaticEx {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		int [] array1 = {1, 5, 7, 9};
		int [] array2 = {3, 6, -1, 100, 77};
		int [] array3 = ArrayUtil.concat(array1, array2);
		ArrayUtil.print(array3);
	}
}

실행 결과
[ 1, 5, 7, 9, 3, 6, -1, 100, 77 ]
import java.util.*;


class ArrayUtil {
	public static int [] concat(int[] a, int[] b) {
		/* 배열 a와 b를 연결한 새로운 배열 리턴 */
		int[] result = new int[a.length+b.length];//a, b 배열의 길이의 합 크기를 가진 새로운 배열 생성
		for(int i = 0; i<a.length; i++) {//배열 a에 저장된 값 새로운 배열에 저장
			result[i] = a[i];
		}
		int j = a.length;//a에 저장된 값 이후 b에 저장된 값을 새로운 배열에 저장하기 위해 result의 위치를 저장하기 위한 변수
		for(int i = 0; i<b.length; i++) {//배열 b에 저장된 값 새로운 배열에 저장
			result[j] = b[i];
			j++;
		}
		return result;//새로운 배열 반환
	}
	public static void print(int[] a) {
		/* 배열 a 출력 */
		System.out.print("[ ");
		for(int i = 0; i<a.length; i++) {//형식에 맞춰 배열에 저장된 값 출력
			System.out.print(a[i]+" ");
		}
		System.out.print("]");
	}
}

public class StaticEx {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		int [] array1 = {1, 5, 7, 9};
		int [] array2 = {3, 6, -1, 100, 77};
		int [] array3 = ArrayUtil.concat(array1, array2);//두 배열을 합친 새로운 배열
		ArrayUtil.print(array3);//배열 출력
	}
}

실행 결과


[10번]

다음과 같은 Dictionary 클래스가 있다. 실행 결과와 같이 작동하도록 Dictionary 클래스의 kor2Eng() 메소드와 DicApp 클래스를 작성하라.

class Dictionary {
	private static String [] kor = {"사랑", "아기", "돈", "미래", "희망"};
	private static String [] eng = {"love", "baby", "money", "future", "hope"};
	public static String kor2Eng(String word) {/*검색 코드 작성*/}
}

실행 결과

한영 단어 검색 프로그램입니다.
한글 단어?희망
희망은 hope
한글 단어?아가
아가는 저의 사전에 없습니다.
한글 단어?아기
아기는 baby
한글 단어?그만
import java.util.*;


class Dictionary {
	private static String [] kor = {"사랑","아기","돈","미래","희망"};
	private static String [] eng = {"love","baby","money","future","hope"};
	public static String kor2Eng(String word) {
		/*검색 코드 작성*/
		String result = "false";//반환을 위한 문장 저장 변수
		int count = 0;//검색 결과 유무에 대한 정보 저장 변수
		for(int i = 0; i<kor.length; i++) {//kor의 크기만큼 반복
			if(kor[i].equals(word)) {//검색할 단어와 저장된 단어가 같은 경우
				result = word+"은 "+eng[i];//문장 저장
				count = 1;//결과 유 표시
			}
		}
		if(count != 1) {//검색 결과가 없는 경우
			result = word+"는 저의 사전에 없습니다.";//문장 저장
			count = 0;//결과 초기화
		}
		return result;//문장 반환
	}
}

public class DicApp {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.println("한영 단어 검색 프로그램입니다.");
		while(true) {//break문 전까지 무한 반복
			System.out.print("한글 단어?");
			String search = scanner.next();//검색할 단어 저장
			if(search.equals("그만")) {//그만을 입력한 경우
				break;//while문에서 벗어나기
			}
			else {
				System.out.println(Dictionary.kor2Eng(search));//검색 결과 출력
			}
		}
	}
}

실행 결과


[11번]

다수의 클래스를 만들고 활용하는 연습을 해보자. 더하기(+), 빼기(-), 곱하기(*), 나누기(/)를 수행하는 각 클래스 Add, Sub, Mul, Div를 만들어라. 이들은 모두 다음 필드와 메소드를 가진다.

  • int 타입의 a, b 필드: 2개의 피연산자
  • void setValue(int a, int b): 피연산자 값을 객체 내에 저장한다.
  • int calculate(): 클래스의 목적에 맞는 연산을 실행하고 결과를 리턴한다.

main() 메소드에서는 다음 실행 사례와 같이 두 정수와 연산자를 입력받고 Add, Sub, Mul, Div 중에서 이 연산을 실행할 수 있는 객체를 생성하고 setValue()와 calculate()를 호출하여 결과를 출력하도록 작성하라. (참고: 이 문제는 상속을 이용하여 다시 작성하도록 5장의 실습문제로 이어진다.)

두 정수와 연산자를 입력하시오>>5 7 *
35
import java.util.*;

class Add {//더하기 클래스
	private int a;
	private int b;
	public void setValue(int a, int b) {//변수 초기화
		this.a = a;
		this.b = b;
	}
	public int calculate() {//더한 값 반환
		return a+b;
	}
}
class Sub {//뺴기 클래스
	private int a;
	private int b;
	public void setValue(int a, int b) {//변수 초기화
		this.a = a;
		this.b = b;
	}
	public int calculate() {//뺀 값 반환
		return a-b;
	}
}
class Mul {//곱하기 클래스
	private int a;
	private int b;
	public void setValue(int a, int b) {//변수 초기화
		this.a = a;
		this.b = b;
	}
	public int calculate() {//곱한 값 반환
		return a*b;
	}
}
class Div {//나누기 클래스
	private int a;
	private int b;
	public void setValue(int a, int b) {//변수 초기화
		this.a = a;
		this.b = b;
	}
	public int calculate() {//나눈 값 반환
		return a/b;
	}
}
public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.print("두 정수와 연산자를 입력하시오>>");
		int a = scanner.nextInt();
		int b = scanner.nextInt();
		String s = scanner.next();//연산자
		if(s.equals("+")) {//더하기인 경우
			Add add = new Add();//객체 생성
			add.setValue(a, b);//변수 저장
			System.out.print(add.calculate());//결과값 출력
		}
		else if(s.equals("-")) {//빼기인 경우
			Sub sub = new Sub();
			sub.setValue(a, b);
			System.out.print(sub.calculate());
		}
		else if(s.equals("*")) {//곱하기인 경우
			Mul mul = new Mul();
			mul.setValue(a, b);
			System.out.print(mul.calculate());
		}
		else if(s.equals("/")) {//나누기인 경우
			Div div = new Div();
			div.setValue(a, b);
			System.out.print(div.calculate());
		}
		
	}
}

실행 결과


[12번]

간단한 콘서트 예약 시스템을 만들어보자. 다수의 클래스를 다루고 객체의 배열을 다루기에는 아직 자바 프로그램 개발이 익숙하지 않은 초보자에게 다소 무리가 있을 것이다. 그러나 반드시 넘어야 할 산이다. 이 도전을 통해 산을 넘어갈 수 있는 체력을 키워보자. 예약 시스템의 기능은 다음과 같다.

  • 공연은 하루에 한 번 있다.
  • 좌석은 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
import java.util.*;

class Seat{//Seat 클래스
	static Scanner scanner;
	private String s[];//s석 
	private String a[];//a석
	private String b[];//b석
	public Seat() {//생성자
		scanner = new Scanner(System.in);
		s = new String[10];//String 타입의 크기가 10인 배열 생성
		a = new String[10];//String 타입의 크기가 10인 배열 생성
		b = new String[10];//String 타입의 크기가 10인 배열 생성
		for(int i = 0; i<10; i++) {
			s[i] = "---";//배열 초기화
			a[i] = "---";
			b[i] = "---";
		}
	}
	public void printSeat(String s, String seat[]) {//seat에 저장된 값 출력을 위한 함수
		System.out.print(s+">>");
		for(int i = 0; i<seat.length; i++) {//seat의 크기만큼 반복
			System.out.print(seat[i]+" ");//저장된 값 출력
		}
		System.out.println();//줄바꿈
	}
	public void printAll() {//s, a, b 전체 출력을 위한 함수
		printSeat("S",s);//s 배열 출력을 위해 printSeat 함수 호출
		printSeat("A",a);//a 배열 출력을 위해 printSeat 함수 호출
		printSeat("B",b);//b 배열 출력을 위해 printSeat 함수 호출
	}
	public void inputSeat(String seat[]) {//좌석 예약(이름, 번호 저장)을 위한 함수
		System.out.print("이름>>");
		String name = scanner.next();//이름 저장
		System.out.print("번호>>");
		int num = scanner.nextInt();//좌석 번호 저장
		num--;//배열 위치와 맞추기 위해 1만큼 감소
		if(num>=0&&num<10) {//0~9에 해당하는 경우
			seat[num] = name;//좌석 번호 위치에 이름 저장
		}
		else {//0~9에 해당하지 않는 경우
			System.out.println("잘못된 자리입니다.");//오류 메시지 출력
		}
	}
	public void reserve() {//예약을 위한 함수
		System.out.print("좌석구분 S(1), A(2), B(3)>>");
		int seatchoice = scanner.nextInt();//선택한 좌석 저장
		if(seatchoice == 1) {//S를 선택한 경우
			printSeat("S",s);//s 배열 출력
			inputSeat(s);//s 좌석 예약 함수 호출
		}
		else if(seatchoice == 2) {//A를 선택한 경우
			printSeat("A",a);//a 배열 출력
			inputSeat(a);//a 좌석 예약 함수 호출
		}
		else if(seatchoice == 3) {//B를 선택한 경우
			printSeat("B",b);//b 배열 출력
			inputSeat(b);//b 좌석 예약 함수 호출
		}
		else {//1~3 범위가 아닌 경우
			System.out.println("없는 번호입니다.");//오류 메시지 출력
		}
	}
	public void cancelseat(String seat[]) {//좌석 취소(이름, 번호 변경)을 위한 함수
		System.out.print("이름>>");
		String name = scanner.next();
		int count = 0;//오류 검출을 위한 변수
		for(int i = 0; i<seat.length; i++) {//배열의 크기만큼 반복
			if(seat[i].equals(name)) {//취소할 이름과 저장된 이름이 같은 경우
				seat[i] = "---";//--- 저장
				count++;//count 값 하나 증가
			}
		}
		if(count == 0) {//배열을 변경하지 않은 경우
			System.out.println("잘못된 취소입니다.");//오류 메시지 출력
		}
		count = 0;
	}
	public void cancel() {//취소를 선택한 경우 실행
		System.out.print("좌석 S:1, A:2, B:3>>");
		int seatlevel = scanner.nextInt();//선택한 좌석 저장
		switch(seatlevel){//seatlevel에 저장된 값에 따라 실행
		case 1: printSeat("S",s); cancelseat(s); break;//s 배열 출력 후, 취소를 위한 함수 호출
		case 2: printSeat("A",a); cancelseat(a); break;//a 배열 출력 후, 취소를 위한 함수 호출
		case 3: printSeat("B",b); cancelseat(b); break;//b 배열 출력 후, 취소를 위한 함수 호출
		default: System.out.println("없는 번호입니다."); break;//1~3 값이 아닌 경우 오류 메시지 출력 후 종료
		}
	}
}

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		Seat seat = new Seat();//객체 생성
		System.out.println("명품콘서트홀 예약 시스템입니다.");
		while(true) {//break문 이전까지 무한 반복
			System.out.print("예약:1, 조회:2, 취소:3, 끝내기:4>>");
			int choice = scanner.nextInt();//선택한 값 저장
			if(choice == 1) {//예약
				seat.reserve();//reserve 함수 호출
			}
			else if(choice == 2) {//조회
				seat.printAll();//printAll 함수 호출
				System.out.println("<<<조회를 완료하였습니다.>>>");
			}
			else if(choice == 3) {//취소
				seat.cancel();//cancel 함수 호출
			}
			else if(choice == 4) {//끝내기
				break;//while문 종료
			}
			else {//1~4 범위가 아닌 경우
				System.out.println("없는 메뉴입니다.");//오류 메시지 출력
			}
		}
	}
}

실행 결과