명품 JAVA Programming 제4강 자바 기본 프로그래밍 실습문제
Programming Language/Java

명품 JAVA Programming 제4강 자바 기본 프로그래밍 실습문제

728x90

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

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

public class TV {
	private String corporation;  //제품 회사
	private int year; //년형
	private int inch; //인치
	
	TV (String corporation, int year, int inch) {
		this.corporation=corporation;
		this.year=year;
		this.inch=inch;
	}
	void show() {
		System.out.println(corporation+"에서 만든 "+year+"년형 "+inch+"인치 TV");
	}

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

		TV myTV=new TV("LG",2017,32);
		myTV.show();
	}

}

 

 

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

public static void main(String[] args) {
		Scanner scaner = new Scanner(System.in);
		
		System.out.print("수학, 과학, 영어 순으로 3개의 점수 입력>>");
		int math=scan.nextInt();
		int science=scan.nextInt();
		int english=scan.nextInt();
		Grade me = new Grade(math,science,english);
		System.out.println("평균은 "+me.average()); //average()는 평균을 계산하여 리턴
		
		scanner.close();
	}
--출력--
수학, 과학, 영어 순으로 3개의 점수 입력>>90 88 96
평균은 91

 

힌트 :

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


import java.util.Scanner;

public class Grade {
	private int math;
	private int science;
	private int english;
	
	Grade(int math,int science,int english) {
		this.math=math;
		this.science=science;
		this.english=english;
	}
	
	int average() {
		int sum=this.math+this.science+this.english;
		return (int)(sum/3);
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan=new Scanner(System.in);
		
		System.out.print("수학, 과학, 영어 순으로 3개의 점수 입력>>");
		int math=scan.nextInt();
		int science=scan.nextInt();
		int english=scan.nextInt();
		Grade me=new Grade(math,science,english);
		System.out.println("평균은 "+me.average());
		
		scan.close();
	}

}

 

 

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

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

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

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

public class Song {
	
	private String title;
	private String artist;
	private int year;
	private 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 static void main(String[] args) {
		// TODO Auto-generated method stub

		Song song=new Song("Dancing Queen","ABBA",1978,"스웨덴");
		song.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) {
		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를 포함합니다.");
}
--출력--
(2,2)에서 크기가 8x7인 사각형
s의 면적은 36
t는 r을 포함합니다.

public class Rectangle {

	private int x;
	private int y;
	private int width;
	private int height;
	
	Rectangle (int x, int y, int width, int height) {
		this.x=x;
		this.y=y;
		this.width=width;
		this.height=height;
	}
	
	int square() {
		return (this.width*this.height);
	}
	
	void show() {
		System.out.println("("+x+","+y+")에서 크기가 "+width+"x"+height+"인 사각형");
	}
	
	boolean contains(Rectangle r) {
		if ((this.x+this.width>r.x+r.width)&&(this.y+this.height>r.y+r.height))
			return true;
		else
			return false;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		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를 포함합니다.");
	}

}

 

 

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

import java.util.Scanner;

class Circle {
	private double x,y;
	private int radius;
	public Circle (double x,double y,int radius) {
		___________________________________; // x, y, radius 초기화
	}
	public void show() {
    	___________________________________; 
	}
}
public class CircleManager {
	public static void main(String[] args) {
		Scanner scanner = ____________________;
		Circle c [] = _______________; // 3개의 Circle 배열 선언
		for(int i=0;i<__________;i++) {
			System.out.print("x, y radius >>");
			_____________________________; // x 값이 읽기
			_____________________________; // y 값이 읽기
			_________________________; // 반지름 읽기
			c[i] = __________________________; // Circle 객체 생성
		}
		for(int i=0;i<c.length;i++) _______________________; // 모든 Circle 객체 출력
		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.Scanner;

class Circle {
	private double x,y;
	private int radius;
	public Circle (double x,double y,int radius) {
		this.x=x;
		this.y=y;
		this.radius=radius;
	}
	public void show() {
		System.out.println("("+x+","+y+")"+radius);
	}
}

public class CircleManager {

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

		Scanner scanner=new Scanner(System.in);
		Circle c[]=new Circle[3];
		for(int i=0;i<c.length;i++) {
			System.out.print("x, y radius >>");
			double x=scanner.nextDouble();
			double y=scanner.nextDouble();
			int radius=scanner.nextInt();
			c[i]=new Circle(x,y,radius);
		}
		for(int i=0;i<c.length;i++)
			c[i].show();
		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.Scanner;

class Circle {
	static int max;
	private double x,y;
	private int radius;
	public Circle_2 (double x,double y,int radius) {
		this.x=x;
		this.y=y;
		this.radius=radius;
	}
	public void show() {
		System.out.println("("+x+","+y+")"+radius);
	}
	
	public void maxArea() {
		if (max<=this.radius)
			max=this.radius;
	}
	
	public void showMaxArea() {
		if (max==this.radius)
			System.out.println("가장 면적이 큰 원은 ("+this.x+","+this.y+")"+this.radius);
	}
}

public class CircleManager {

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

		Scanner scanner=new Scanner(System.in);
		Circle_2 c[]=new Circle_2[3];
		for(int i=0;i<c.length;i++) {
			System.out.print("x, y radius >>");
			double x=scanner.nextDouble();
			double y=scanner.nextDouble();
			int radius=scanner.nextInt();
			c[i]=new Circle_2(x,y,radius);
		}
		for(int i=0;i<c.length;i++)
			c[i].maxArea();
		
		for(int i=0;i<c.length;i++)
			c[i].showMaxArea();

		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개의 기능을 작성하라. 

--출력--
이번달 스케쥴 관리 프로그램.
할일(입력:1, 보기:2, 끝내기:3) >>1
날짜(1~30)?1
할일(빈칸없이입력)?자바공부

할일(입력:1, 보기:2, 끝내기:3) >>2
날짜(1~30)?1
1일의 할 일은 자바공부입니다.

할일(입력:1, 보기:2, 끝내기:3) >>3
프로그램을 종료합니다.

 

힌트 :

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

MonthSchedule april = new MonthSchedule(30); //4월달의 할 일
april.run( );

import java.util.Scanner;

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+"입니다.");
	}
}

public class MonthSchedule {

	Scanner scan=new Scanner(System.in);
	Day d[];
	
	public MonthSchedule(int day) {
		d=new Day[day];
		for(int i=0;i<day;i++)
			d[i]=new Day();
	}
	
	void input(Day d[],int day, String work) {
		d[day].set(work);
	}
	
	void view(Day d[],int day) {
		System.out.print(day+"일의 할 일은 ");
		d[day].show();
	}
	
	int finish() {
		System.out.println("프로그램을 종료합니다.");
		return 0;
	}
	
	void run() {
		int t=1;
		int option;
		int day;
		String work;
		System.out.println("이번달 스케쥴 관리 프로그램.");
		
		while(t==1) {
			System.out.print("할일(입력:1, 보기:2, 끝내기:3) >>");
			option=scan.nextInt();
			switch (option) {
			case 1:
				System.out.print("날짜(1~30)?");
				day=scan.nextInt();
				System.out.print("할일(빈칸없이입력)?");
				work=scan.next();
				this.input(this.d,day,work);
				System.out.println();
				break;
			case 2:
				System.out.print("날짜(1~30)?");
				day=scan.nextInt();
				this.view(this.d,day);
				System.out.println();
				break;
			case 3:
				t=this.finish();
				break;
			}
		}	
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		MonthSchedule april=new MonthSchedule(30);
		april.run();
	}

}
728x90

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

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

 

힌트 :

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


import java.util.Scanner;

class Phone {
	
	private String name;
	private String phoneNumber;
	
	Phone (String name, String phoneNumber) { //Phone 생성자
		this.name=name;
		this.phoneNumber=phoneNumber;
	}
	
	boolean getNumber (String name) { //인자로 받은 이름이 객체의 이름과 같으면 번호 출력 후 true 반환
		if (this.name.equals(name)) {
			System.out.println(name+"의 번호는 "+this.phoneNumber+" 입니다.");
			return true;
		}
		else
			return false;
	}
}

public class PhoneBook {
	
	private Phone phone[];
	int i;
	boolean tf;
	
	PhoneBook (int num) { //PhoneBook 생성자
		phone=new Phone[num];
	}
	
	void bookSet (int num, String name, String phoneNumber) { //객체 배열의 각 객체 생성
		phone[num]=new Phone(name,phoneNumber);
	}
	
	void show (String name) { //객체 배열 중 인자로 받은 name과 동일한 name이 있는지 확인
		for(i=0;i<this.phone.length;i++) {
			tf=phone[i].getNumber(name);
			if (tf==true)
				break;
		}
		if (i==this.phone.length)
			System.out.println(name+" 이 없습니다.");
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan=new Scanner(System.in);
		
		int num;
		String name;
		String phoneNumber;
		
		System.out.print("인원수>>");
		num=scan.nextInt();
		PhoneBook phoneBook=new PhoneBook(num); //PhoneBook 객체 생성
		
		for(int i=0;i<num;i++) {
			System.out.print("이름과 전화번호(이름과 번호는 빈 칸없이 입력)>>");
			name=scan.next();
			phoneNumber=scan.next();
			phoneBook.bookSet(i,name,phoneNumber); //Phone 객체 배열 생성
		}
		System.out.println("저장되었습니다...");
		
		while(true) {
			System.out.print("검색할 이름>>");
			name=scan.next();
			if (name.equals("그만"))
				break;
			phoneBook.show(name);
		}
	}

}

 

 

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

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) {
		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 ]

class ArrayUtil {
	
	static int[] c;
	
	public static int [] concat(int[] a, int[] b) {
		c=new int[a.length+b.length];
		int i;
		for (i=0;i<a.length;i++)
			c[i]=a[i];
		for (i=0;i<b.length;i++)
			c[i+a.length]=b[i];
		return c;
	}
	
	public static void print(int[] a) {
		System.out.print("[ ");
		for(int i=0;i<a.length;i++) {
			System.out.print(a[i]+" ");
		}
		System.out.println("]");
	}
}
public class StaticEx {

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

		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.Scanner;

class DicApp {
	
	Scanner scan=new Scanner(System.in);
	String word;
	
	DicApp() {
		System.out.println("한영 단어 검색 프로그램입니다.");
		while(true) {
			System.out.print("한글 단어?");
			word=scan.next();
			
			if (word.equals("그만"))
				break;
			else
				System.out.println(Dictionary.kor2Eng(word));
		}
	}
	
	
}
class Dictionary {

	private static String [] kor = { "사랑", "아기", "돈", "미래", "희망" };
	private static String [] eng = { "love", "baby", "money", "future", "hope" };
	
	public static String kor2Eng(String word) {
		int i;
		String ans="";
		
		for (i=0;i<kor.length;i++) {
			if (kor[i].equals(word)) {
				ans=(word+"은 "+eng[i]);
				break;
			}

		}
		if (i==kor.length)
			ans=(word+"는 저의 사전에 없습니다.");
		return ans;
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		DicApp dicApp=new DicApp();
	}

}

 

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.Scanner;

class Add {
	private int a;
	private int b;
	
	void setValue(int a, int b) {
		this.a=a;
		this.b=b;
	}
	
	int calculate() {
		return this.a+this.b;
	}
}

class Sub {
	private int a;
	private int b;
	
	void setValue(int a, int b) {
		this.a=a;
		this.b=b;
	}
	
	int calculate() {
		return this.a-this.b;
	}
}

class Mul {
	private int a;
	private int b;
	
	void setValue(int a, int b) {
		this.a=a;
		this.b=b;
	}
	
	int calculate() {
		return this.a*this.b;
	}
}

class Div {
	private int a;
	private int b;
	
	void setValue(int a, int b) {
		this.a=a;
		this.b=b;
	}
	
	int calculate() {
		return this.a/this.b;
	}
}

public class Calculate {

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

		Scanner scan=new Scanner(System.in);
		int num1;
		int num2;
		String oper;
		
		System.out.print("두 정수와 연산자를 입력하시오>>");
		num1=scan.nextInt();
		num2=scan.nextInt();
		oper=scan.next();
		
		switch (oper) {
		case "+":
			Add add=new Add();
			add.setValue(num1,num2);
			System.out.println(add.calculate());
			break;
		case "-":
			Sub sub=new Sub();
			sub.setValue(num1,num2);
			System.out.println(sub.calculate());
			break;
		case "*":
			Mul mul=new Mul();
			mul.setValue(num1,num2);
			System.out.println(mul.calculate());
			break;
		case "/":
			Div div=new Div();
			div.setValue(num1,num2);
			System.out.println(div.calculate());
			break;
		}
	}

}

 

 

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 Reservation {
	Scanner scan=new Scanner(System.in);
	
	Reservation(String S[],String A[],String B[]) {
		int option;
		String name;
		int seat;
		
		while (true) {
			try {
			System.out.print("좌석구분 S(1), A(2), B(3)>>");
			option=scan.nextInt();
			}
			catch (InputMismatchException e) {
				System.out.println("잘못 입력. 다시 입력하시오.");
				scan.nextLine();
				continue;
			}
			if (option==1) {
				System.out.print("S>>"); //현재 S석 상태 출력
				for (int i=0;i<S.length;i++)
					System.out.print(" "+S[i]);
				System.out.println();
				System.out.print("이름>>"); //예약자 이름 입력
				name=scan.next();
				while(true) { //좌석 번호 입력(좌석 번호 범위 초과 시 오류 메시지)
					try {
						System.out.print("번호>>");
						seat=scan.nextInt();
					}
					catch (InputMismatchException e) {
						System.out.println("잘못 입력. 다시 입력하시오.");
						scan.nextLine();
						continue;
					}
					if ((seat>=1)&&(seat<=10)) {
						if (S[seat].equals("---")) //빈자리면 예약 진행
							S[seat]=name;
						else {
							System.out.println("이미 예약된 자리입니다. 다시 입력하세요.");
							continue;
						}
						break;
					}
					else {
						System.out.println("자리번호는 1~10까지 입니다. 다시 입력해 주세요.");
						continue;
					}
				}
				break;
			}
			else if (option==2) {
				System.out.print("A>>"); //현재 A석 상태 출력
				for (int i=0;i<A.length;i++)
					System.out.print(" "+A[i]);
				System.out.println();
				System.out.print("이름>>"); //예약자 이름 입력
				name=scan.next();
				while(true) { //좌석 번호 입력(좌석 번호 범위 초과 시 오류 메시지)
					try {
						System.out.print("번호>>");
						seat=scan.nextInt();
					}
					catch (InputMismatchException e) {
						System.out.println("잘못 입력. 다시 입력하시오.");
						scan.nextLine();
						continue;
					}
					System.out.print("번호>>");
					seat=scan.nextInt();
					if ((seat>=1)&&(seat<=10)) {
						if (A[seat].equals("---")) //빈자리면 예약 진행
							A[seat]=name;
						else {
							System.out.println("이미 예약된 자리입니다. 다시 입력하세요.");
							continue;
						}
						break;
					}
					else {
						System.out.println("자리번호는 1~10까지 입니다. 다시 입력해 주세요.");
						continue;
					}
				}
				break;
			}
			else if (option==3) {
				System.out.print("B>>"); //현재 B석 상태 출력
				for (int i=0;i<B.length;i++)
					System.out.print(" "+B[i]);
				System.out.println();
				System.out.print("이름>>"); //예약자 이름 입력
				name=scan.next();
				while(true) { //좌석 번호 입력(좌석 번호 범위 초과 시 오류 메시지
					try {
						System.out.print("번호>>");
						seat=scan.nextInt();
					}
					catch (InputMismatchException e) {
						System.out.println("잘못 입력. 다시 입력하시오.");
						scan.nextLine();
						continue;
					}
					System.out.print("번호>>");
					seat=scan.nextInt();
					if ((seat>=1)&&(seat<=10)) {
						if (B[seat].equals("---")) //빈자리면 예약 진행
							B[seat]=name;
						else {
							System.out.println("이미 예약된 자리입니다. 다시 입력하세요.");
							continue;
						}
						break;
					}
					else {
						System.out.println("자리번호는 1~10까지 입니다. 다시 입력해 주세요.");
						continue;
					}
				}
				break;
			}
			else
				System.out.println("잘못 입력. 다시 입력해주세요.");
		}
	}

	
}

class Check {
	Check(String S[],String A[], String B[]) {
		
		System.out.print("S>>"); //S좌석 출력
		for (int i=0;i<10;i++)
			System.out.print(" "+S[i]);
		System.out.println();

		System.out.print("A>>"); //A좌석 출력
		for (int i=0;i<10;i++)
			System.out.print(" "+A[i]);
		System.out.println();
		
		System.out.print("B>>"); //B좌석 출력
		for (int i=0;i<10;i++)
			System.out.print(" "+B[i]);
		System.out.println();

		System.out.println("<<조회를 완료하였습니다>>");
	}
}

class Cancel {
	Cancel (String S[],String A[],String B[]) {
		Scanner scan=new Scanner(System.in);
		int option;
		String name;
		int seat;
		
		while (true) {
			try {
				System.out.print("좌석 S:1, A:2, B:3>>");
				option=scan.nextInt();
			}
			catch (InputMismatchException e) {
				System.out.println("잘못 입력. 다시 입력하시오.");
				scan.nextLine();
				continue;
			}
			if (option==1) {
				System.out.print("S>>"); //현재 S석 상태 출력
				for (int i=0;i<S.length;i++)
					System.out.print(" "+S[i]);
				System.out.println();
				while(true) {
					System.out.print("이름>>"); //예약자 이름 입력
					name=scan.next();
					int i;
					for (i=0;i<S.length;i++) { //해당하는 이름 있으면 삭제
						if (S[i].equals(name)) {
							S[i]="---";
							break;
						}	
					}
					if (i==S.length) {
						System.out.println("예약 내역이 없습니다. 다시 입력해 주세요.");
						continue;
					}
					break;
				}
				break;
			}
			else if (option==2) {
				System.out.print("A>>"); //현재 A석 상태 출력
				for (int i=0;i<A.length;i++)
					System.out.print(" "+A[i]);
				System.out.println();
				while(true) {
					System.out.print("이름>>"); //예약자 이름 입력
					name=scan.next();
					int i;
					for (i=0;i<A.length;i++) { //해당하는 이름 있으면 삭제
						if (A[i].equals(name)) {
							A[i]="---";
							break;
						}	
					}
					if (i==A.length) {
						System.out.println("예약 내역이 없습니다. 다시 입력해 주세요.");
						continue;
					}
					break;
				}
				break;
			}
			else if (option==3) {
				System.out.print("B>>"); //현재 B석 상태 출력
				for (int i=0;i<B.length;i++)
					System.out.print(" "+B[i]);
				System.out.println();
				while(true) {
					System.out.print("이름>>"); //예약자 이름 입력
					name=scan.next();
					int i;
					for (i=0;i<B.length;i++) { //해당하는 이름 있으면 삭제
						if (B[i].equals(name)) {
							B[i]="---";
							break;
						}	
					}
					if (i==B.length) {
						System.out.println("예약 내역이 없습니다. 다시 입력해 주세요.");
						continue;
					}
					break;
				}
				break;
			}
			else
				System.out.println("잘못 입력. 다시 입력해주세요.");
		}
	}

}

public class ConcertReservationSystem {
	static String S[]=new String[10];
	static String A[]=new String[10];
	static String B[]=new String[10];

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

		Scanner scan=new Scanner(System.in);
		int option;
		System.out.println("명품콘서트홀 예약 시스템입니다.");
		for(int i=0;i<10;i++) { //세 좌석 타입 모두 빈자리로 초기화
			S[i]="---";
			A[i]="---";
			B[i]="---";
		}
		
		while (true) {
			try {
				System.out.print("예약:1. 조회:2, 취소:3, 끝내기:4>>");
				option=scan.nextInt();
			}
			catch (InputMismatchException e) {
				System.out.println("잘못 입력. 다시 입력하시오.");
				scan.nextLine();
				continue;
			}
			if (option==1) { //예약
				Reservation reservation=new Reservation(S,A,B);
				continue;
			}
			else if (option==2) { //조회
				Check check=new Check(S,A,B);
				continue;
			}
			else if (option==3) { //취소
				Cancel cancel=new Cancel(S,A,B);
				continue;
			}
			else if (option==4)//끝내기
				break;
			else {
				System.out.println("잘못 입력. 다시 입력해주세요.");
				continue;
			}
		}
	}
}

 

내 생각 :

중간중간 try-catch문은 꼭 넣지 않아도 된다고 생각한다.

근데 실행시켜 보다가 숫자를 입력하려다가 잘못 눌러 문자를 눌렀을 때, 에러 메시지가 뜨며 실행이 종료된다.

그러면 실행을 처음부터 다시 해야 한다.

이 부분이 싫어서 try-catch문으로 숫자를 입력해야 되는데 문자를 입력했을 경우,

경고 메시지를 입력하고 다시 입력을 받을 수 있게 해 주었다.

 

근데 이 try-catch문을 구현하다가 무한 반복에 빠지는 문제가 생겼었다.

↓처음 짠 try-catch문 중 하나↓

try {
	System.out.print("좌석구분 S(1), A(2), B(3)>>");
	option=scan.nextInt();
}
catch (InputMismatchException e) {
	System.out.println("잘못 입력. 다시 입력하시오.");
	continue;
}

숫자를 입력받아야 되는데 문자를 입력하면 이 try-catch문이 무한 반복되었다.

구글링을 열심히 해보니,

option=scan.nextInt();

이 부분에서 에러가 생기지 않았다면, scanner에 입력받아진 문장이 option에 저장되고 scanner가 비워진다.

하지만 try-catch에서 에러를 catch 해서 catch{ }문으로 수행이 넘어가고 scanner는 비워지지 않는다.

catch{ }문의 수행이 끝나고 다시 try{}문으로 넘어오면 비워지지 않은 scanner 때문에 다시 에러가 catch되고 다시 catch{ }문으로 수행이 넘어간다.

이런 식으로 무한 반복에 빠지게 된다.

 

따라서 다음 문장을 catch{ }문에 추가해주었다.

scan.nextLine();

scanner를 비워주는 문장이다.

↓제대로 동작하는 try-catch문↓

try {
	System.out.print("좌석구분 S(1), A(2), B(3)>>");
	option=scan.nextInt();
}
catch (InputMismatchException e) {
	System.out.println("잘못 입력. 다시 입력하시오.");
	scan.nextLine();
	continue;
}

 

 

Open Challenge 끝말잇기 게임 만들기

n명이 참가하는 끝말잇기 게임을 만들어보자. 처음 단어는 "아버지"이다. n명의 참가자들은 순서대로 자신의 단어를 입력하면 된다. 끝말잇기에서 끝말이 틀린 경우 게임을 끝내고 게임에서 진 참가자를 화면에 출력한다. 프로그램에서는 시간 지연을 구현하지 않아도 된다. 그렇지만 참가자들이 스스로 시간을 재어보는 것도 좋겠다. 이 문제의 핵심은 여러 개의 객체와 배열 사용을 연습하기 위한 것으로, main( )을 포함하는 WordGameApp 클래스와 각 선수를 나타내는 Player 클래스를 작성하고, 실행 중에는 WordGameApp 객체 하나와 선수 숫자만큼의 Player 객체를 생성하는 데 있다. 문제에 충실하게 프로그램을 작성하여야 실력이 늘게 됨을 알기 바란다.

--출력--
끝말잇기 게임을 시작합니다...
게임에 참가하는 인원은 몇명입니까>>3
참가자의 이름을 입력하세요>>황기태
참가자의 이름을 입력하세요>>이재문
참가자의 이름을 입력하세요>>한원선
시작하는 단어는 아버지입니다.
황기태>>지우게
이재문>>게다리
한원선>>리본
황기태>>본죽
이재문>>족발
이재문이 졌습니다.

 

힌트 :

  • WordGameApp, Player의 두 클래스를 작성하는 것을 추천한다. WordGameApp 클래스에는 생성자, main( ), 게임을 전체적으로 진행하는 run( ) 메소드를 둔다. run( )에서는 선수 숫자만큼의 Player 객체를 배열로 생성한다.
  • Player 클래스는 게임 참가자의 이름 필드와 사용자로부터 단어를 입력받는 getWordFromUser( ) 메소드, 끝말잇기의 성공 여부와 게임을 계속하는지를 판별하는 checkSuccess( ) 메소드를 두면 좋겠다.
  • 문자열의 마지막 문자와 첫 번째 문자는 다음과 같이 알아낼 수 있다.
String word="아버지";
int lastIndex=word.length()-1; // 마지막 문자에 대한 인덱스
char lastChar=word.charAt(lastIndex); // 마지막 문자
char firstChar=word.charAt(0); //  번째 문자

import java.util.Scanner;

class Player {
	Scanner scan=new Scanner(System.in);
	private String name;
	private String word;
	
	Player(String name) {
		this.name=name;
	}
	
	String getPlayerName() {
		return this.name;
	}
	
	String getWordFromUser() {
		System.out.print(this.name+">>");
		this.word=scan.next();
		return this.word;
	}
	
	boolean checkSuccess (char lastChar) {
		boolean result;
		char firstChar=this.word.charAt(0);
		if (lastChar==firstChar)
			result=true;
		else
			result=false;
		return result;
	}
}
public class WordGameApp {
	static Scanner scan=new Scanner(System.in);
	String word="아버지";
	int lastIndex;
	char lastChar;
	boolean result;
	
	WordGameApp() {}
	
	void run(int num) {
		String name;
		Player player[]=new Player[num];
		
		for (int i=0;i<player.length;i++) { //참가자 이름 입력
			System.out.print("참가자의 이름을 입력하세요>>");
			name=scan.next();
			player[i]=new Player(name);
		}
		
		System.out.println("시작하는 단어는 아버지입니다.");
		while(true) {
			for (int i=0;i<player.length;i++) {
				lastIndex=word.length()-1;
				lastChar=word.charAt(lastIndex);
				word=player[i].getWordFromUser();
				result=player[i].checkSuccess(lastChar);
				if (result==false) {
					System.out.println(player[i].getPlayerName()+"이 졌습니다.");
					break;
				}
			}
			if (result==false)
				break;
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		WordGameApp wordGameApp=new WordGameApp();
		int num;
		
		System.out.println("끝말잇기 게임을 시작합니다...");
		System.out.print("게임에 참가하는 인원은 몇명입니까>>");
		num=scan.nextInt();
		wordGameApp.run(num);
	}

}
728x90