명품 JAVA Programming 연습문제 4장
1. 노래를 나타내는 Song이라는 클래스를 설게하라. Song클래스는 다음과 같은 필드를 갖는다.
0 노래의 제목을 나타내는 title
0 가수를 나타내는 artist
0 노래가 속한 앨범 제목을 나타내는 album
0 노래의 작곡가를 나타내는 composer, 작곡가는 여러 명 있을 수 있다.
0 노래가 발표된 연도를 나타내는 year
0 노래가 속한 앨범에서의 트랙 번호를 나타내는 track
생성자는 기본 생성자와 모든 필드를 초기화하는 생성자를 작성하고, 노래의 정보를 화면에 출력하는 show() 메소드도 작성하라. ABBA 의 “Dancing Queen”노래를 Song 객체로 생성하고 show()를 이용하여 이 노래의 정보를 출력하는 프로그램을 작성하라.
public class Song
{
public String title
public String artist
public String album
public String composer
public String year
public String track
public Song()
{
}
public Song(int x)
{
if( x == 0)
{
title = "입력 초기화"
artist = "입력 초기화"
album = "입력 초기화"
composer = "입력 초기화"
year = "입력 초기화"
track = "입력 초기화"
}
}
public void show(Song x)
{
System.out.println(title);
System.out.println(artist);
System.out.println(album);
System.out.println(composer);
System.out.println(year);
System.out.println(track);
}
public static void main(String[] args)
{
Song DancingQueen;
DancingQueen = new Song();
DancingQueen.title = "Dancing Queen"
DancingQueen.artist = "ABBA"
DancingQueen.album = "The Album"
DancingQueen.composer = "ABBA"
DancingQueen.year = "2007"
DancingQueen.track = "2"
DancingQueen.show(DancingQueen);
DancingQueen = new Song(0);
DancingQueen.show(DancingQueen);
}
}
2. 다음과 같은 맴버를 가지는 직사각형을 표현하는 Rectangle 클래스를 작성하라.
0 int 타입의 x1,y1,x2,y2 필드 : 사각형을 구성하는 두 점의 좌표
0 생성자 2개 : 디폴트 생성자와 x1,y1,x2,y2의 값을 설정하는 생성자
void set(int x1, int y1, int x2, int y2) : x1, y1, x2, y2 좌표 설정
0 in square() : 사각형 넓이 리턴
void show() : 좌표와 넓이 등 직사각형 정보의 화면 출력
boolean equals(Rectangle r) : 인자로 전달된 객체 r과 현 객체가 동일한 직사각형이면 true리턴
Rectangle을 이용한 main() 메소드는 다음과 같으며 이 main()메소드가 잘 작동하도록 하라.
public static void main(String[] args)
{
Rectangle r = new Rectangle();
Rectangle s = new Rectangle(1,1,2,3);
r.show();
s.show();
System.out.println(s.square());
r.set(-2,2,-1,4);
r.show();
System.out.println(r.square());
if(r.equals(s))
{
System.out.println("두 사각형은 같습니다.");
}
}
public class Rectangle
{
int x1,x2,y1,y2,sum
public Rectangle()
{
}
public Rectangle(int x1, int y1, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
sum = (x2-x1) * (y2-y1);
System.out.println("");
}
void set(int x1, int y1, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
sum = (x2-x1) * (y2-y1);
System.out.println("");
}
int square()
{
int a,b,sum;
a =x2-x1
b =y2-y1
sum = a*b;
return sum;
}
void show()
{
System.out.println("좌표값 :" +"(" + x1 +","+ y1 +")"+ "(" + x2 +","+ y2 +")");
System.out.println("넓이 :" + sum);
System.out.println("");
}
boolean equals(Rectangle r)
{
if(sum == r.sum)
{
return true
}
return false
}
public static void main(String[] args)
{
Rectangle r = new Rectangle();
Rectangle s = new Rectangle(1,1,2,3);
r.show();
s.show();
System.out.println(s.square());
r.set(-2,2,-1,4);
r.show();
System.out.println(r.square());
if(r.equals(s))
{
System.out.println("두 사각형은 같습니다.");
}
}
}
3. 다음 두 개의 static 메소드를 가진 ArrayUtility 클래스를 만들어보자. ArrayUtility 클래스를 이용하는 테스트용 프로그램도 함께 작성하라.
static double[] intToDouble(int [] source); // int 배열을 double 배열로 변환
static int[] doubleToInt(double [] source); // double배열을 int 배열로 변환
public class ArrayUtility
{
int[] int_a = {1,2,3,4,5,6,7,8,9,10};
double[] double_a= {1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5};
public static double[] intToDouble(int[] x)
{
double[] j = new double[x.length];
for(int i = 0; i <x.length i++)
{
j[i] = (double)x[i];
System.out.print(j[i]+",");
}
return j;
}
public static int[] doubleToInt(double[] x)
{
int[] j = new int[x.length];
for(int i = 0; i <x.length i++)
{
j[i] = (int)x[i];
System.out.print(j[i]+",");
}
return j;
}
public ArrayUtility()
{
}
public static void main(String[] args)
{
ArrayUtility A = new ArrayUtility();
System.out.println("Int 형을 double 형으로 변환 하기 " + intToDouble(A.int_a));
System.out.println("double 형을 Int 형으로 변환하기 " + doubleToInt(A.double_a));
}
}
4. 다음 두 개의 static 메소드를 가진 ArrayUtility2 클래스를 만들어보자. ArrayUtility2 클래스를 이용하는 테스트용 프로그램도 함께 작성하라.
static int[] concat(int [] s1, int [] s2); // s1과 s2를 연결한 새로운 배열 리턴
static int[] remove(int [] s1, int [] s2); // s1에서 s2 배열의 숫자를 모두 삭제한 새로운 배열 리턴
5.다수의 클래스를 정의하고 활용하느 sdustmq을 해 보자. 더하기(+), 빼기(-), 곱하기(*), 나누기(/)를 수행하는 각 클래서 Add, Sub, Mul, Div를 만들어라. 이들은 모두 다음 필드와 메소드를 가진다.
0 int 타입의 a,b 필드 : 연산하고자 하는 피 연산자
0 void setValue(int a, int b) : 피연산자를 객체 내에 설정한다.
0 int calculate(): 해당 클래스의 목적에 맞는 연산을 실행하고 그 결과를 리턴한다.
int a int a int a int a
int b int b int b int b
setValue() setValue() setValue() setValue()
Calculate() Calculate() Calculate() Calculate()
Add Sub Mul Div
main() 메소드에서는 다음 실행 사례의 그림과 같이 키보드로부터 두 정수와 계산하고자 하는 연산자를 입력받은 후 Add, Sub, Mul, Div 중에서 이 연산을 실행할 수 있는 객체를 생성하고 setValue()와 calculate()를 호출하여 그 결과 값을 화면에 출력한다.
import java.util.Scanner;
public class calculate
{
public static void main(String[] agrs)
{
Scanner input = new Scanner(System.in);
Add A = new Add();
Sub S = new Sub();
Mul M = new Mul();
Div D = new Div();
System.out.println("두 정수와 연산자를 입력하시오>>");
int a = input.nextInt();
int b = input.nextInt();
char c = input.next().charAt(0);
switch(c)
{
case '+' :
{
A.setValue(a, b);
System.out.println(A.calculate());
break
}
case '-' :
{
S.setValue(a, b);
System.out.println(S.calculate());
break
}
case '*' :
{
M.setValue(a, b);
System.out.println(M.calculate());
break
}
case '/' :
{
D.setValue(a, b);
System.out.println(D.calculate());
break
}
}
}
}
class Add
{
private int a, 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, 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, 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, b
public void setValue(int a, int b)
{
this.a = a;
this.b = b;
}
public int calculate()
{
return a / b
}
}
6.간단한 공연 예약 시스템을 만들어보자. 다수의 클래스를 다루고 객체의 배열을 다루기에는 아직 자바로 프로그램 개발이 익숙하지않은 초보자에게 다소 무리가 있을 것이다. 그러나 반드시 넘어야 할 산이다. 이 도전 주제를 통해 산을 넘어갈 수 있는 체력을 키워보자. 공연 에약 시스템의 내용은 다음과 같다,
0 공연은 하루에 한 번 있다.
0 좌석은 S석, A석, B석 타입ㅇ ㅣ있으며 모두 10석의 좌석이 있다.
0 공연 예약 시스템의 메뉴는 “예약”, “조회”, “취소”, “끝내기”가 있다.
0 예약은 한 자리만 예약할 수 있고 좌석 타입, 예약자 이름, 좌석 번호를 순서대로 입력받아야 한다.
0 조회는 모든 종류의 좌석을 표시한다.
0 취소는 예약자의 이름을 입력하여 취소한다.
0 없는 이름, 없는 번호, 없는 메뉴, 잘못된 취소 등에 대해서 오류 메시지를 출력하고 사용자가 다시 시도하도록 한다.
import java.util.Scanner;
public class Reserve
{
public static void main(String[] args)
{
Concent c = new Concent();
int choice;
while(true)
{
System.out.println("예약(1), 조회(2), 취소(3), 끝내기(4) >>");
Scanner s = new Scanner(System.in);
try
{
choice = Integer.parseInt( s.nextLine() );
if( choice < 1 || choice > 4 )
throw new Exception();
}
catch(Exception e)
{
System.out.println("잘못선택 하였습니다 다시 선택 하여 주세요");
continue
}
switch(choice)
{
case 1 : c.reserve();break
case 2 : c.SeatsAll();break
case 3 : System.out.print("이름>>");
String name = s.nextLine();
if(c.cancle(name)) System.out.println("예약을 취소되었습니다.");
else System.out.println("예약된 이름이 없습니다.");
break
case 4 : return
}
}
}
}
class Concent
{
String[][] seats = new String[3][10];
public Concent()
{
for(int i = 0; i <3; i++)
{
for(int j = 0; j < 10; j ++)
{
seats[i][j] = "___"
}
}
}
public void reserve ()
{
int seat;
while(true)
{
System.out.println("좌석구분 S석(1), A석(2), B석(3) >>");
Scanner s = new Scanner(System.in);
try
{
seat = Integer.parseInt( s.nextLine() );
if( seat < 1 || seat > 3 )
throw new Exception();
}
catch(Exception e)
{
System.out.println("잘못선택 하였습니다 다시 선택 하여 주세요.");
continue
}
printSeats(seat-1);
System.out.print("이름>> ");
String name = s.nextLine();
if(Name(name));
else { System.out.println("이미 예약된 이름입니다."); continue}
System.out.println("좌석 번호>>");
int num = s.nextInt();
try
{
if(num < 1 || num>10)
throw new Exception();
}
catch(Exception e)
{
System.out.println("좌석은 1번부터 10번까지 있습니다.");
continue
}
if( Num(seat-1, num-1, name) )
{
System.out.println("<<예약을 완료하였습니다.>>");
}
else
{
System.out.println("<<이미 예약된 좌석입니다.>>");
continue
}
break
}
}
public boolean Name(String name)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 10; j++)
{
if(seats[i][j].equals(name))return false
}
}
return true
}
public void printSeats(int seat)
{
String L = null
switch (seat)
{
case 0 : L = "S석" break
case 1 : L = "A석" break
case 2 : L = "B석" break
}
System.out.print(L + ">> ");
for(int i=0 ; i<10 ; i++)
{
System.out.print( seats[seat][i] + " ");
}
System.out.println();
}
public boolean Num(int seat, int num, String name)
{
if( seats[seat][num].equals("___") )
{
seats[seat][num] = name;
return true
}
else
{
return false
}
}
public void SeatsAll()
{
for(int i = 0; i < 3; i++) printSeats(i);
}
public boolean cancle(String name)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 10; j++)
{
if(seats[i][j].equals(name))
{
seats[i][j] = "___"
return true
}
}
}
return false
}
}
'IT > 프로그래밍' 카테고리의 다른 글
명품 JAVA Programming 연습문제 11장 (0) | 2020.11.29 |
---|---|
명품 JAVA Programming 연습문제 10장 (0) | 2020.11.29 |
명품 JAVA Programming 연습문제 9장 (0) | 2020.11.29 |
명품 JAVA Programming 연습문제 5장 (0) | 2020.11.28 |
명품 JAVA Programming 연습문제 2장 (0) | 2020.11.28 |
댓글