1. 자바 클래스 작성하는 연습을 해보자. 다음 main() 메소드를 실행했을 때 예시와 같이 출력되도록 TV 클래스를 작성하라.
import java.util.*;
class TV {
String brand;
int year, inches;
public TV(String brand, int year, int inches) {
this.brand = brand;
this.year = year;
this.inches = inches;
}
public void show() {
System.out.print(brand + "에서 만든 " + year + "년형 " + inches + "인치 TV");
}
}
public class CH4 {
Scanner s = new Scanner(System.in);
public static void main(String [] args) {
TV myTV = new TV("LG", 2017, 32); // LG에서 만든 2017년 32인치
myTV.show();
}
}
2. Grade클래스를 작성해보자. 3과목의 점수를 입력받아 Grade객체를 생성하고, 성적 평균을 출력하는 main()과 실행 예시는 다음과 같다.
import java.util.*;
class Grade {
int math, science, english;
public Grade(int a, int b, int c) {
this.math = a;
this.science = b;
this.english = c;
}
int average() {
return (math + science + english) / 3;
}
}
public class CH4 {
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
System.out.print("수학, 과학, 영어 순으로 3개의 점수 입력 >> ");
int math = s.nextInt();
int science = s.nextInt();
int english = s.nextInt();
Grade me = new Grade(math, science, english);
System.out.println("평균은 " + me.average());
s.close();
}
}
3. 노래 한 곡을 나타내는 Song클래스를 작성하라. Song은 다음 필드로 구성된다.
class Song {
String title, artist, country;
int year;
// 기본생성자
public Song() {
}
// 매개변수로 모든 필드 초기화시키는 생성자
public Song(String a, String b, int c, String d) {
this.title = a;
this.artist = b;
this.year = c;
this.country = d;
}
void show() {
System.out.print(year + "년 " + country + "국적의 " + artist + "가 부른 " + title);
}
}
public class CH4 {
public static void main(String [] args) {
Song s1 = new Song("Dancing Queen", "ABBA", 1978, "스웨덴");
s1.show();
}
}
4. 다음 멤버를 가지고 직사각형을 표현하는 Rectangle클래스를 작성하라.
import java.util.*;
class Rectangle {
int x,y,width,height;
public Rectangle(int a,int b,int c,int d) {
this.x = a;
this.y = b;
this.width = c;
this.height = d;
}
int square() {
return width*height;
}
void show() {
System.out.println("(" + x + "," + y + ")에서 크기가 " + width + "x" + height + "인 사각형");
}
boolean contains(Rectangle r) { // 여기서 사각형들은, x,y좌표에서 시작, height만큼 위로, width만큼 오른쪽으로 만들어짐.
if ( (x < r.x) && (y < r.y) && ((x+width) > (r.x+r.width)) && ((y+height) > (r.y+r.height)) )
return true;
else
return false;
}
}
public class CH4 {
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를 포함합니다.");
}
}
5. 다음 설명대로 Circle클래스와 CircleManager클래스를 완성하라.
import java.util.*;
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 CH4 {
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
Circle c[] = new Circle[3]; // 3개의 Circle배열 선언
for (int i = 0; i<3 ; i++) {
System.out.print("x, y, radius >> ");
double x = s.nextDouble();
double y = s.nextDouble();
int radius = s.nextInt();
c[i] = new Circle(x, y, radius);
}
for (int i = 0; i<c.length; i++) {
c[i].show();
}
s.close();
}
}
6. 앞의 5번 문제는 정답이 공개되어 있다. 이 정답을 참고하여 Circle클래스와 CircleManager클래스를 수정하여 다음 실행 결과처럼 되게 하라.
import java.util.*;
class Circle {
public double x,y;
public 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 CH4 {
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
Circle c[] = new Circle[3]; // 3개의 Circle배열 선언
for (int i = 0; i<3 ; i++) {
System.out.print("x, y, radius >> ");
double x = s.nextDouble();
double y = s.nextDouble();
int radius = s.nextInt();
c[i] = new Circle(x, y, radius);
}
// 가장 큰 원을 c[0]라 가정하고, c[1]과 c[2]와 순서대로 비교 후, 현재 가장 큰 원보다 더 큰 원이 있으면 교체.
int biggest_circle = 0; // 객체배열에 있는 객체들 중 가장 큰 원의 인덱스 = 0
for (int i = 1; i<=2; i++) {
if (c[biggest_circle].radius < c[i].radius)
biggest_circle = i;
}
System.out.print("가장 면적이 큰 원은 (" + c[biggest_circle].x + "," + c[biggest_circle].y + ")" + c[biggest_circle].radius);
s.close();
}
}
7. 하루 할 일을 표현하는 클래스 Day는 다음과 같다. 한 달의 할 일을 표현하는 MonthSchedule클래스를 작성하라.
import java.util.*;
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 {
Day days[];
public MonthSchedule(int m_days) {
days = new Day[m_days];
for (int i = 0; i<m_days; i++) {
days[i] = new Day();
}
}
void input(Scanner s) { // 메뉴 1번 - 입력
System.out.print("날짜(1~30)? ");
int day = s.nextInt();
System.out.print("할일(빈칸없이 입력)? ");
String todo = s.next();
days[day].set(todo);
System.out.println();
}
void view(Scanner s) { // 메뉴 2번 - 보기
System.out.print("날짜(1~30)? ");
int day = s.nextInt();
days[day].show();
System.out.println();
}
void finish() { // 메뉴 3번 - 끝내기
System.out.println("프로그램을 종료합니다.");
}
void run() { // 메뉴출력 및 처리하는 메소드
System.out.println("이번달 스케쥴 관리 프로그램");
while (true) {
Scanner s = new Scanner(System.in);
System.out.print("할 일 (입력:1 / 보기:2 / 끝내기:3) >> ");
int choose = s.nextInt();
switch (choose) {
case 1:
input(s);
continue;
case 2:
view(s);
continue;
case 3:
finish();
break;
}
break;
}
}
public static void main(String [] args) {
MonthSchedule april = new MonthSchedule(30);
april.run();
}
}
8. 이름(name), 전화번호(tel) 필드와 생성자 등을 가진 Phone클래스를 작성하고, 실행 예시와 같이 작동하는 PhoneBook클래스를 작성하라.
import java.util.*;
class Phone {
public String name, tel;
public Phone(String name, String tel) {
this.name = name;
this.tel = tel;
}
}
public class PhoneBook {
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
System.out.print("인원수 >> ");
int nums = s.nextInt();
Phone phone[] = new Phone[nums];
for (int i =0; i<nums; i++) {
System.out.print("이름과 전화번호(이름과 번호는 빈 칸없이 입력) >> ");
String name = s.next();
String tel = s.next();
phone[i] = new Phone(name, tel);
}
System.out.println("저장되었습니다. . .");
while(true) {
int i = 0;
System.out.print("검색할 이름 >> ");
String search = s.next();
if ( search.equals("그만") == true ) {
System.out.println("프로그램을 종료합니다.");
break;
}
for (i = 0; i<nums; i++) {
if ( search.equals( phone[i].name ) == true ) {
System.out.println(phone[i].name + "의 번호는 " + phone[i].tel + " 입니다.");
break;
}
}
if (i == nums)
System.out.println(search + "이(가) 없습니다.");
}
s.close();
}
}
9. 다음 2개의 static메소드를 가진 ArrauUtil클래스를 만들어보자. 다음 코드의 실행 결과를 참고하여 concat()와 print()를 작성하여 ArrayUtil클래스를 완성하라.
import java.util.*;
class ArrayUtil {
public static int [] concat(int[] a, int[] b) {
int i, j;
// 매개변수(배열)로 받은 a배열과 b배열의 길이를 합하고,
// 그 합만큼의 길이를 갖는 int형 배열 comp를 생성.
int comp[] = new int[a.length+b.length];
for (i = 0; i<a.length; i++) // a.length만큼의 공간에 a배열의 값들을 순서대로 집어넣음.
comp[i] = a[i];
for (j = i; j<comp.length; j++) { // 남은 공간에 b배열의 값들을 순서대로 집어넣음
comp[j] = b[j-i];
}
return comp; // 만들어진 합성배열 comp를 리턴
}
// 배열을 출력하는 메소드
public static void print(int[] 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) {
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클래스를 작성하라.
import java.util.*;
class Dictionary {
private static String kor[] = { "사랑", "아기", "돈", "미래", "희망" };
private static String eng[] = { "love", "baby", "money", "future", "hope" };
public static String kor2Eng(String word) {
int i;
for (i =0; i<kor.length; i++) {
if (word.equals(kor[i]) == true)
return eng[i];
}
return "NULL";
}
}
public class DicApp {
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
String result;
System.out.println("한영 단어 검색 프로그램입니다.");
while (true) {
System.out.print("한글 단어? ");
String search = s.next();
if (search.equals("그만") == true) {
System.out.println("프로그램을 종료합니다");
break;
}
else
result = Dictionary.kor2Eng(search);
if (result.equals("NULL"))
System.out.println(search + "는 저의 사전에 없습니다.");
else
System.out.println(search + "은(는) " + result);
}
s.close();
}
}
11. 다수의 클래스를 만들고 활용하는 연습을 해보자.
import java.util.*;
class Add {
int a,b;
void setValue(int a, int b) {
this.a = a; this.b = b;
}
int calculate() {
return a+b;
}
}
class Sub {
int a,b;
void setValue(int a, int b) {
this.a = a; this.b = b;
}
int calculate() {
return a-b;
}
}
class Mul {
int a,b;
void setValue(int a, int b) {
this.a = a; this.b = b;
}
int calculate() {
return a*b;
}
}
class Div {
int a,b;
void setValue(int a, int b) {
this.a = a; this.b = b;
}
int calculate() {
return a/b;
}
}
public class Calculate {
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
System.out.print("두 정수와 연산자를 입력하시오 >> ");
int num1 = s.nextInt();
int num2 = s.nextInt();
String calc = s.next();
switch (calc) {
case "+":
Add add = new Add();
add.setValue(num1, num2);
System.out.print(add.calculate());
break;
case "-":
Sub sub = new Sub();
sub.setValue(num1, num2);
System.out.print(sub.calculate());
break;
case "*":
Mul mul = new Mul();
mul.setValue(num1, num2);
System.out.print(mul.calculate());
break;
case "/":
Div div = new Div();
div.setValue(num1, num2);
System.out.print(div.calculate());
break;
}
s.close();
}
}
12. 간단한 콘서트 예약 시스템 (근데 이제 하나도 안 간단한)
import java.util.Scanner;
class Csystem {
static int chairs = 10; // 10은 줄당 좌석 갯수, 1은 S>>, A>>, B>>도 행렬에 포함시켜버리기 위한 추가 공간
String SAB[][] = new String[3][chairs];
// 생성자
public Csystem() {
for (int i = 0; i<3; i++) {
for (int j = 0; j<chairs; j++)
SAB[i][j] = "---";
}
}
// 1번 메뉴 (예약)
void reserve(Scanner s) {
int lineSAB;
while (true) { // S,A,B 잘못 입력 시 다시 입력하도록 함.
System.out.print("좌석구분 S(1), A(2), B(3) >> ");
lineSAB = s.nextInt();
if (lineSAB <= 3 && lineSAB > 0)
break;
else {
System.out.println("<<<잘못된 입력입니다. 1~3사이의 번호를 다시 입력하십시오.>>>");
System.out.println();
}
}
switch (lineSAB) {
case 1:
System.out.print("S>> ");
break;
case 2:
System.out.print("A>> ");
break;
case 3:
System.out.print("B>> ");
break;
}
for (int i =0; i<chairs; i++)
System.out.print(SAB[lineSAB-1][i] + " ");
System.out.println();
String name;
int num;
System.out.print("이름 >> ");
name = s.next();
while (true) { // 좌석 번호 잘못입력할 경우 다시 입력하도록 함.
System.out.print("번호 >> ");
num = s.nextInt();
if (num <= 10 && num >= 1)
break;
else {
System.out.println("<<<잘못된 입력입니다. 1~10사이의 번호를 다시 입력하십시오.>>>");
System.out.println();
}
}
SAB[lineSAB-1][num-1] = name; // 위에서 인덱스 기준이 아닌, 좌석 표시 기준으로 num을 입력했으므로 -1
System.out.println();
System.out.println("========================================");
System.out.println(" <<<예약이 완료되었습니다.>>>");
System.out.println(" <<<메인메뉴로 돌아갑니다.>>>");
System.out.println("========================================");
System.out.println();
}
// 2번 메뉴 (조회)
void check() {
// S행 인쇄
System.out.print("S>> ");
for (int j = 0; j<chairs; j++)
System.out.print(SAB[0][j] + " ");
System.out.println();
System.out.print("A>> ");
for (int j = 0; j<chairs; j++)
System.out.print(SAB[1][j] + " ");
System.out.println();
System.out.print("B>> ");
for (int j = 0; j<chairs; j++)
System.out.print(SAB[2][j] + " ");
System.out.println();
System.out.println();
System.out.println("========================================");
System.out.println(" <<<조회를 완료하였습니다.>>>");
System.out.println(" <<<메인메뉴로 돌아갑니다.>>>");
System.out.println("========================================");
System.out.println();
}
// 3번 메뉴 (취소)
void cancel(Scanner s) {
System.out.print("예약하신 이름을 입력해주십시오. >> ");
String name = s.next();
for (int i = 0; i<3; i++) {
for (int j = 0; j<chairs; j++) {
if (SAB[i][j].equals(name)) {
SAB[i][j] = "---";
System.out.println();
System.out.println("========================================");
System.out.println(" 선택하신 예매표가 취소되었습니다.");
System.out.println(" 메인메뉴로 돌아갑니다. ");
System.out.println("========================================");
System.out.println();
return;
}
}
}
System.out.println();
System.out.println("========================================");
System.out.println("<<<입력하신 이름으로 예약된 좌석을 찾지 못했습니다.>>>");
System.out.println("<<< 메인메뉴로 돌아갑니다. >>>");
System.out.println("========================================");
System.out.println();
}
// 4번 메뉴 (끝내기)
void offsystem() {
System.out.println("========================================");
System.out.println(" <<<명품콘서트홀 예약 시스템을 종료합니다.>>>");
System.out.println("========================================");
}
}
public class Concert {
public static void main(String [] args) {
Scanner s = new Scanner(System.in);
System.out.println("========================================");
System.out.println(" 명품콘서트홀 예약 시스템입니다.");
System.out.println("========================================");
Csystem csystem = new Csystem();
while (true) {
int choose;
System.out.println("메뉴를 선택해주십시오");
while (true) {
System.out.print("예약:1, 조회:2, 취소:3, 끝내기:4 >> ");
choose = s.nextInt();
if (choose >= 1 && choose <= 4)
break;
else {
System.out.println("<<<잘못된 입력입니다. 1~4사이의 번호를 다시 입력해주십시오.>>>");
System.out.println();
}
}
switch (choose) {
case 1:
csystem.reserve(s);
break;
case 2:
csystem.check();
break;
case 3:
csystem.cancel(s);
break;
case 4:
csystem.offsystem();
return;
}
}
}
}
'명품 자바 프로그래밍' 카테고리의 다른 글
명품 자바 프로그래밍 6장 오픈챌린지 영문자 히스토그램 만들기 (1) | 2023.11.12 |
---|---|
명품 자바 프로그래밍 5장 실습문제 (2) | 2023.10.22 |
명품 자바 프로그래밍 4장 오픈챌린지 끝말잇기 게임 만들기 (0) | 2023.10.21 |
명품자바프로그래밍 3장 실습문제 (1) | 2023.10.07 |
명품 자바 프로그래밍 159P 3장 오픈챌린지 카드 번호 맞추기 게임 (0) | 2023.09.24 |